Editor

Build a Basic argparse CLI

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 lesson

Create an argparse-based greeting tool:

1. Create an ArgumentParser with description 'Greeting tool'

2. Add a positional argument name

3. Add an optional argument --greeting with default 'Hello'

4. Parse the args ['World', '--greeting', 'Hi']

5. Print the result in the format <greeting>, <name>!

Expected output: Hi, World!

import argparse
# Build the parser and parse arguments

More argparse exercises

All Python exercises · 50 practice problems · Advanced Python quiz