Back to results for “Command-Line Interfaces (argparse)”
Python › Command-Line Interfaces (argparse)

What is the difference between a positional argument and an optional argument (flag) in argparse?

Beginner

Answer

A positional argument is REQUIRED and identified by its ORDER on the command line (declared without a leading dash); an optional argument is identified by a FLAG name (starting with '-' or '--') and is optional by default unless you explicitly mark it 'required=True'.
parser.add_argument("filename")               # positional: required, identified by position
parser.add_argument("--verbose", action="store_true")  # optional: identified by --verbose flag

# python script.py data.txt --verbose
Real-world example Requiring a filename as a positional argument while making a --verbose logging flag optional.

Common follow-ups: How would you make an optional-looking flag (like --output) actually REQUIRED?