And the output: 

$ python3 prog.py 4-v3 usage: prog.py [-h] [-v {0,1,2}] square prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, $ python3 prog.py 4-h usage: prog.py [-h] [-v {0,1,2}] square positional arguments: square display a square of a given number optional arguments: -h, --help show this help message and exit -v {0,1,2}, --verbosity {0,1,2} increase output verbosity 

Note that the change also reflects both in the error message as well as the help string. 

Now, let’s use a different approach of playing with verbosity, which is pretty common. It also matches the way the CPython executable handles its own verbosity argument (check the output of$_{python --help}$ ): 

import argparse parser =argparse.ArgumentParser() parser.add_argument( "square",type=int, help="display the square of a given number ") parser.add_argument( "-v ","--verbosity ", action="count", help="increase output verbosity ") args =parser.parse_args() answer =args.square**2 if args.verbosity ==2: print("the square of {} equals {} ".format(args .square, answer)) elif args.verbosity ==1: print(" {} ^2 == {} ".format(args .square, answer)) else : print(answer) 

We have introduced another action, “count”, to count the number of occurrences of a specific optional arguments: 

$ python3 prog.py 4 16 $ python3 prog.py 4-v 4^2 == 16 $ python3 prog.py 4-vv the square of 4 equals 16 $ python3 prog.py 4--verbosity --verbosity the square of 4 equals 16 $ python3 prog.py 4-v1 usage: prog.py [-h] [-v] square prog.py: error: unrecognized arguments: 1 $ python3 prog.py 4-h usage: prog.py [-h] [-v] square positional arguments: square display a square of a given number optional arguments: -h, --help show this help message and exit -v, --verbosity increase output verbosity $ python3 prog.py 4-vvv 16 

• Yes, it’s now more of a flag (similar to$_{action="store_true"}$ ) in the previous version of our script. That should explain the complaint. 

