[Python] Parse named command-line options with argparse

Created on November 30, 2026

The standard-library argparse module parses options such as --name. Save this example as greet.py.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name", required=True)
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args()

for _ in range(args.count):
    print(f"Hello, {args.name}!")
python3 greet.py --name Taro --count 2
Hello, Taro!
Hello, Taro!

required=True makes --name mandatory. type=int converts --count to an integer, and default=1 supplies the value when it is omitted.

python3 greet.py --name Taro
Hello, Taro!

A missing name or an invalid count produces an error and exit status 2. Run python3 greet.py --help to see the options.

References

Python