By the end of this lesson
Use argparse for a typed argument and observe success or failure.
Before you start
- Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
- Complete lesson 17 in this route, or be comfortable with its examples.
Three words to know
- Argument parser
- A component that translates command-line text into named values.
- stdout
- The ordinary output stream.
- Exit status
- A number returned to the caller; zero conventionally means success.
1. Define the interface
Save the source as lesson.py. argparse provides --help and rejects missing or malformed arguments. type=int converts text but does not enforce our positive range, so the program adds that rule explicitly. Argument parsing happens inside main so importing the file does not parse another program’s arguments.
import argparse
def main():
parser = argparse.ArgumentParser(description="Describe a page count.")
parser.add_argument("pages", type=int)
args = parser.parse_args()
if not 1 <= args.pages <= 50:
parser.error("pages must be between 1 and 50")
print(f"Checking {args.pages} pages")
if __name__ == "__main__":
main()
What you should see · example output
Checking 4 pages
2. Run valid and invalid cases
python3 lesson.py 4
What you should see · example output
Checking 4 pages
Try --help, apple and 0 instead of 4. Help exits successfully; parse and range errors write a message to stderr and exit with status 2. The exact help layout can vary between Python versions. On Windows use py -3 in place of python3.
3. Observe status in your shell
python3 lesson.py 0
printf "exit=%s\n" "$?"
What you should see · example output
An error message, then exit=2
In PowerShell, run the command and then inspect $LASTEXITCODE. Exit status belongs to the process, not the text of its message. A caller should not have to guess failure by searching stdout for the word error.
YOUR TURN
A small check before you continue
Does type=int alone reject -1? Where does our program reject it?
Show a suggested answer
The conversion accepts -1. The explicit 1 <= args.pages <= 50 check rejects it with parser.error and status 2.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
