How to make the argument optional in Python

PythonServer Side ProgrammingProgramming

Introduction..

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...

Example

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 {args.name}")

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 test.py -h
usage: test.py [-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.

>>>python test.py
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 test.py --name Universe
Hello Universe

>>> python test.py --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
raja
Published on 10-Nov-2020 05:32:18
Advertisements