argparse: arguments, defaults and --help
The prog name in the usage line is main.py. parse_args receives a fixed list so the example is repeatable.
A command-line tool reads its settings from the words typed after its name. Python's argparse module turns sys.argv into a clean object, builds --help for free, rejects bad input with a usage message, and lets the program report success or failure through its exit code.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a parser for a tool repeat with a positional word and an option --count (integer, default 2), and print the word that many times on one line.
Add a --upper flag to it.
Write main(argv) that returns 0 on success and 1 if --count is below 1 (print an error to sys.stderr).
Explain it without notes
What is the difference between a positional argument, an option and a flag in argparse?
What are exit codes, and what does argparse do on bad input?
How do you build a tool with subcommands, and how do you test it without a terminal?
Why do many tools read secrets from the environment rather than a --api-key option?
Expected output
Namespace(name='Asha', times=2, shout=True)
HELLO, ASHA!
HELLO, ASHA!
Namespace(name='Ben', times=1, shout=False)
usage: main.py [-h] [--times TIMES] [--shout] name
Greet someone.
positional arguments:
name who to greet
options:
-h, --help show this help message and exit
--times TIMES how many greetings
--shout use capital letters