Command-Line Arguments
Pass information to a script when you run it
In this lesson
When you launch a program from the terminal. Python report.py sales.csv, anything you type after the script name is handed straight to your program as a command-line argument. Reading those arguments is what lets one script work on any file or value instead of a hard-coded one. It's the difference between a one-off and a reusable tool.
Explain it like I’m 5
It's like ordering at a counter. The program is the order, ‘make a coffee’, and the command-line arguments are the choices you add: ‘…large, oat milk’. Same program, different details each time you run it.
What command-line arguments are
import sys
print(sys.argv)
$ python args.py hello 42 ['args.py', 'hello', '42']
Reading an argument safely
If the user runs your script with no arguments, sys.argv holds only the script name — so reaching for sys.argv[1] would raise an IndexError. Check how many arguments arrived with len(sys.argv) first, and fall back to a sensible default when one is missing.
import sys
name = sys.argv[1] if len(sys.argv) > 1 else "World"
print(f"Hello, {name}!")
$ python greet.py Ada Hello, Ada! $ python greet.py Hello, World!
Arguments are always strings
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
print(a + b)
$ python add.py 2 3 5
Checking the count and showing usage
A polished tool tells people how to use it. Compare len(sys.argv) against what you expect, print a short usage line when it's wrong, and stop with sys.exit(1), the 1 signals ‘something went wrong’ to the terminal.
import sys
if len(sys.argv) != 2:
print("Usage: python greet.py <name>")
sys.exit(1)
print(f"Hello, {sys.argv[1]}!")
$ python greet.py Usage: python greet.py <name>
When you outgrow sys.argv: argparse
Reading sys.argv by hand is perfect for one or two simple arguments. Once a script grows real options, a flag here, an optional output name there — the standard-library argparse module takes over the tedious parts. You declare the arguments you want; it parses them, converts types, generates a --help screen, and prints a friendly error when someone gets it wrong.
You don't need it yet, but it's worth knowing where the road leads. It's exactly the upgrade suggested in the CSV Cleaner project.
import argparse
parser = argparse.ArgumentParser(description="Greet someone.")
parser.add_argument("name")
parser.add_argument("--shout", action="store_true")
args = parser.parse_args()
greeting = f"Hello, {args.name}!"
print(greeting.upper() if args.shout else greeting)
$ python tool.py Ada --shout HELLO, ADA!
Common mistake: Reading sys.argv[1] when no argument was given
With no arguments, sys.argv contains only the script name, so index 1 doesn't exist and Python raises IndexError.
Check len(sys.argv) before indexing, or supply a default with a conditional expression such as sys.argv[1] if len(sys.argv) > 1 else "default".
Common mistake: Doing math on arguments without converting them
Everything in sys.argv is a string, so sys.argv[1] + sys.argv[2] joins the text ('2' + '3' → '23') instead of adding.
Convert each value with int() or float(), ideally inside try/except, before calculating.
import sys
# "2" + "3" would give "23", not 5
total = int(sys.argv[1]) + int(sys.argv[2])
print(total)
What does sys.argv[0] contain?
Index 0 is always the script's own name; the arguments you pass start at index 1.
What type are the values in sys.argv?
Command-line arguments are always strings. Use int() or float() to do arithmetic with them.
Mini exercise (medium)
Write area.py that takes a width and a height on the command line and prints their product. Running python area.py 5 4 should print 20.
There’s no command line in the browser, so we simulate the arguments as a list, exactly what sys.argv[1:] would give you. Read the width and height and print their product.
args = ["5", "4"] # like running: python area.py 5 4
width = 0 # TODO: convert args[0]
height = 0 # TODO: convert args[1]
area = width * height
print(area)
sys.argv[1] and sys.argv[2] are strings, wrap each in int() before multiplying.
args = ["5", "4"]
width = int(args[0])
height = int(args[1])
area = width * height
print(area)
assert area == 20, "convert the args with int() before multiplying"
print("✓ Correct!")