Chapters
Python114 chapters

Exercises

Command-line Arguments

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Build a parser taking a required name, and print it.

Python
import argparse
# build the parser and parse ["Ada"]
Exercise 2

Add a --times option that converts to an integer, and print the greeting that many times.

Python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("name")
# add --times

args = parser.parse_args(["Ada", "--times", "2"])
for _ in range(args.times):
    print("Hello,", args.name)
Exercise 3

Add a --loud flag that takes no value, and print whether it was given.

Python
import argparse

parser = argparse.ArgumentParser()
# add --loud

print(parser.parse_args(["--loud"]).loud)
print(parser.parse_args([]).loud)