ArgumentParser.add_argument()
Now, let us look at the .add_argument()
method of ArgumentParser
, which is arguably (see what I did there?) one of the most important methods.
Again, I would like you to take a look at the documentation. You will learn better by exploring these on your own!
Here are some highlights:
As we have seen, you can set the type of the argument (what does it default to if not specified?). You can also restrict its possible values. You can obviously do both!
parser.add_argument("x", type=int)
parser.add_argument("operation", choices=['add', 'sub', 'mul', 'div'])
parser.add_argument("z", type=int, choices=[1, 2, 3, 4, 5])
You can also add a more helpful message. The generated help for our calculator program does not tell us what x
or y
or operation
do. Perhaps we can make our help message more useful?
Your task: Modify calculator.py
to give a more useful description for the three arguments!
$ python3 calculator.py -h
usage: Type in python3 calculator.py x y operation
Best calculator in the world, period.
positional arguments:
x The first number to use in the calculation.
y The second number to use in the calculation.
{add,sub,mul,div} The operation to perform on x and y.
optional arguments:
-h, --help show this help message and exit
That is all I have to say!