Type Validation and Choices
Intermediate · Write the code · from Build Command-Line Tools with argparse and sys.argv
From the lesson: Build Command-Line Tools with argparse and sys.argv
Most Python scripts you've written so far run the same way every time. But what if you want the user to choose what your script does? That's where command-line arguments come in. Instead of hardcoding values, you let users pass them when they run your script.
Read the lessonCreate a calculator CLI with argparse:
1. Add two positional arguments a and b, both with type=float
2. Add an optional argument --op with choices=['add', 'sub', 'mul'] and default='add'
3. Parse ['10', '3', '--op', 'mul']
4. Compute and print the result
Expected output: 30.0
import argparse
# Build a calculator CLI
More argparse exercises
- Parse sys.argv ManuallyIntermediate
- Build a Basic argparse CLIIntermediate
- Fix the argparse BugIntermediate
- Build a Subcommand CLIIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz