Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
103: Standard Input and Command-Line Arguments
A few years ago, I was reviewing code for a junior developer who had written a great script to analyze server logs. The logic was flawless, but there was one problem: every time he wanted to analyze a different log file, he opened the .py file, manually changed a hardcoded string like filename = "server_log_monday.txt" to "server_log_tuesday.txt", and saved it. When I asked him why he didn't just pass the filename as an argument, he looked at me like I was speaking a foreign language. He had spent hours over a month just editing a single line of text. It was a classic case of writing a program that works, but isn't actually a tool.
Conversing with the User via input()
Sometimes, you want your program to pause and wait for the user to tell it something while it's already running. That's where input() comes in. It's a straightforward function that prints a prompt to the screen and halts execution until the user hits Enter. I often use this for simple configuration prompts or confirmation checks (like "Are you sure you want to delete this file? y/n").
# A quick example of a dynamic greeting and age check
name = input("Who am I speaking with? ")
age_str = input("And how old are you? ")
# Remember: input() always returns a string.
# If you need a number, you have to cast it.
age = int(age_str)
if age < 18:
print(f"Sorry, {name}, you're too young for this script!")
else:
print(f"Welcome aboard, {name}.")
One thing that trips people up is forgetting that input() is strictly for strings. If you try to perform math on the result without wrapping it in int() or float(), Python will throw a TypeError. It's a small detail, but it's one of those things you'll likely forget at least once in your first week.
Powering Up with sys.argv
While input() is great for interactive scripts, it's a nightmare for automation. If you're scheduling a script to run via a cron job or a CI/CD pipeline, there's no human there to type into a prompt. This is where command-line arguments come in. You provide the data at the moment you launch the script.
To do this, we use the sys module. Specifically, sys.argv, which is essentially a list of all the strings passed to the script from the terminal. The first element, sys.argv[0], is always the name of the script itself. The actual data you care about starts at index 1.
import sys
# Let's say we run this as: python analyzer.py data.csv 100
if len(sys.argv) < 3:
print("Usage: python analyzer.py [filename] [threshold]")
sys.exit(1) # Exit with an error code
filename = sys.argv[1]
threshold = int(sys.argv[2])
print(f"Processing {filename} with a threshold of {threshold}...")
# Logic to open the file and filter data would go here
I prefer sys.argv for simple tools, but be warned: as your tools grow, managing a list of indices becomes confusing. If you find yourself checking sys.argv[7], it's time to look into the argparse library. For now, though, mastering sys.argv is the fastest way to turn your scripts into actual command-line utilities.
📋 Practical Task
Build a Command-Line Word Counter
Your task is to create a script called word_count.py that allows a user to specify a text file and a "target word" via command-line arguments. The script should then count how many times that specific word appears in the file.
Requirements:
- The script must take two arguments: the path to a
.txtfile and the word to search for. - If the user fails to provide both arguments, the script should print a usage message (e.g.,
Usage: python word_count.py <file> <word>) and exit. - The script should read the file, count the occurrences of the word (case-insensitive), and print the final count.
- Handle the case where the file might not exist by using a
try-exceptblock to catchFileNotFoundError.
Testing your tool:
Create a file named sample.txt with some text in it, then run your script from the terminal:
python word_count.py sample.txt python
There are no comments for now.