4 Introducing Optional arguments (continues on next page) 5 $ python3 prog.py --verbose verbosity turned on $ python3 prog.py --verbose 1 usage: prog.py [-h] [--verbose] prog.py: error: unrecognized arguments: 1 $ python3 prog.py --help usage: prog.py [-h] [--verbose] optional arguments: import argparse parser =argparse.ArgumentParser() parser.add_argument( "--verbose ", help="increase output verbosity ", action="store_true") args =parser.parse_args() if args.verbose: print("verbosity turned on") $ python3 prog.py --verbosity 1 verbosity turned on $ python3 prog.py $ python3 prog.py --help usage: prog.py [-h] [--verbosity VERBOSITY] optional arguments: -h, --help show this help message and exit --verbosity VERBOSITY increase output verbosity $ python3 prog.py --verbosity usage: prog.py [-h] [--verbosity VERBOSITY] prog.py: error: argument --verbosity: expected one argument import argparse parser =argparse.ArgumentParser() parser.add_argument( "--verbosity ", help="increase output verbosity ") args =parser.parse_args() if args.verbosity: print("verbosity turned on") So far we have been playing with positional arguments. Let us have a look on how to add optional ones: And the output: Here is what is happening: The above example accepts arbitrary integer values for$_{--verbosity}$ , but for our simple program, only two values are actually useful,$_{True}$ or$_{False}$. Let’s modify the code accordingly: • When using the$_{--verbosity}$ option, one must also specify some value, any value. • The help message is a bit different. • To show that the option is actually optional, there is no error when running the program without it. Note that by default, if an optional argument isn’t used, the relevant variable, in this case$_{args.verbosity}$ , is given None as a value, which is the reason it fails the truth test of the$_{if}$ statement. • The program is written so as to display something when$_{--verbosity}$ is specified and display nothing when not. And the output: