This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Optional arguments

So far, we have only talked about positional arguments.

We can also allow users to specify optional arguments. These are like keyword arguments in functions. Users specify the keywords and values, and you can also provide default values for them.

The options (i.e. keywords) start with - or --. You saw an example optional argument with -h or --help.

Let’s say we want to give users the option of changing the base of the calculator output, say maybe to base 8. We will allow the user to specify the option --base followed by 8 for this.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int)
parser.add_argument("y", type=int)
parser.add_argument("operation", choices=['add', 'sub', 'mul', 'div'])
parser.add_argument("--base", type=int)
args = parser.parse_args()
print(args.base)

...

And the script is called as follows (both works):

$ python3 calculator.py 4 6 add --base 8
$ python3 calculator.py --base 8 4 6 add

Shorthand

You can also specify a shorthand, for example -b, along with --base.

parser.add_argument("-b", "--base", type=int)

And the script can be called as follows:

$ python3 calculator.py 4 6 add -b 8

Default value

You can also specify a default value, for when the user does not specify --base.

parser = argparse.ArgumentParser()
parser.add_argument("--base", default=10)
args = parser.parse_args()
print(args.base)