Editor

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 lesson

The code below has bugs that prevent it from working correctly. Fix the issues so it prints:

Searching for: python
Max results: 5
Verbose: True
import 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

All Python exercises · 50 practice problems · Advanced Python quiz