How to make the argument optional in Python


Sometimes, the programs require optional arguments when supplied will use them else go back to default declarations. We will see in this example on how to use them.

The parameters that start with dashes (--) are identified as optional, so they can be left out, and they may have default values.

Parameters that don’t start with dashes are positional and are usually required, so they do not have default values.

How to do it...


import argparse
parser = argparse.ArgumentParser(description='Optional Argument Example')
parser.add_argument('-n', '--name', metavar='name',
default='World', help='Say Hello to <>')
args = parser.parse_args()
print(f"Hello {}")

The “metavar” will show up in the usage to describe the argument while the -n and --name are described for the “short” and “long” option names.

1. Let us see the help message first before execution.

>>>python -h
usage: [-h] [-n name]

Optional Argument Example

optional arguments:
-h, --help show this help message and exit
-n name, --name name Say Hello to <<name>>

2. Run the program without passing any parameters.

Hello World

3. Pass the Universe name to say hello. Remember if you want to use the optional parameter, specify the value using --name or -n

>>>python --name Universe
Hello Universe

>>> python --n Universe
Hello Universe

To conclude, remeber below points.

Type        Example                    Required       Default
Optional   -n (short), --name (long)    No            Yes
Positional  name or number, ..          Yes No