Fix the argparse Bug
Intermediate · Fix the bug · 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 lessonThe code below has bugs that prevent it from working correctly. Fix the issues so it prints:
Searching for: python
Max results: 5
Verbose: Trueimport argparse
parser = argparse.ArgumentParser()
parser.add_argument('query')
parser.add_argument('--max', type=str, default=5)
parser.add_argument('--verbose', action='store_false')
args = parser.parse_args(['python', '--max', '5', '--verbose'])
print(f'Searching for: {args.query}')
print(f'Max results: {args.max}')
print(f'Verbose: {args.verbose}')
More argparse exercises
- Parse sys.argv ManuallyIntermediate
- Build a Basic argparse CLIIntermediate
- Type Validation and ChoicesIntermediate
- Build a Subcommand CLIIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz