
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to make the argument optional in Python
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
- Related Articles
- How to pass optional parameters to a function in Python?
- How to pass argument to an Exception in Python?
- How to define Optional Methods in the Swift Protocol?
- How to specify optional properties in TypeScript?
- Argument Parsing in Python
- How to restrict argument values using choice options in Python?
- How to pass a dictionary as argument in Python function?
- How to call a function with argument list in Python?
- How to pass Python function as a function argument?
- How optional chaining works in TypeScript?
- How can I pass optional or keyword parameters from one function to another in Python?
- Return the angle of the complex argument in Python
- Argument of an Exception in Python
- Change the real part of the complex argument in Python
- Return the imaginary part of the complex argument in Python
