How to use one or more same positional arguments in Python?


If we were writing a program that performs arithematic operations on two numbers, we could define them as two positional arguments. But since they are the same kinds/python data types of arguments, it might make more sense to use the nargs option to tell argparse that you want exactly two of same types.

How to do it..

1. Let's write a program to substract two numbers (both the arguments are of same type).


import argparse

def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.

2. type - The actual Python data type
- (note the lack of quotes around str)

3. help - A brief description of the parameter for the usage

4. nargs - require exactly nargs values.


parser = argparse.ArgumentParser(
description='Example for nargs',

help='Numbers of type int for subtraction')

return parser.parse_args()

def main():
args = get_args()
num1, num2 = args.numbers
print(f" *** Subtracting two number - {num1} - {num2} = {num1 - num2}")

if __name__ == '__main__':
  • The nargs=2 will require exactly two values.

  • Each value must be send as an integer value else our program will error out.

Let us run the program by passing different values.


<<< python 30 10
*** Subtracting two number - 30 - 10 = 40

<<< python 30 10
*** Subtracting two number - 30 - 10 = 20

<<< python 10 30
*** Subtracting two number - 10 - 30 = -20

<<< python 10 10 30
usage: [-h] int int error: unrecognized arguments: 30

<<< python
usage: [-h] int int error: the following arguments are required: int

Updated on: 10-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started