Search⌘ K
AI Features

Adding Arguments

Understand how to use Python's argparse to add required and optional arguments, set default values, specify types, and handle errors in command-line input for effective argument parsing.

Arguments can be of multiple types. Here we are going to discuss required and optional arguments.

Required and optional arguments

Let’s write some code that adds three new arguments that our parser can understand. We will add three arguments; one of them is required, and the other two are not. We’ll also look at adding default and a required type. Example code is given below.

Let’s test multiple commands in the below terminal. Start with:

Python 3.5
python3 arg_demo2.py

The output would be:

usage: arg_demo2.py [-h] -x X [-y Y] [-z Z]
arg_demo2.py: error: the following
...