What are argparse names or flags in Python?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors.

The parse_args() function of the ArgumentParser class parses arguments, and the add_argument() function adds arguments to be accepted from the user.

The first argument for the add_argument() function must be either a name or a series of flags. This tells the function to expect a positional argument or an optional argument like -f.

Example

The following example demonstrates how to use required command-line arguments.

The program program.py takes two command-line arguments. The ArgumentParser object parser is created to add arguments and parse them.

  • The program adds a positional argument foo by supplying a name to the add_argument() function.
  • The program adds another argument, radius, and leaves it as an optional argument. The add_argument() function knows that the argument radius is optional because the first argument for this function is a flag.
import argparse
#create an ArgumentParser object
parser = argparse.ArgumentParser(description = 'Calculate radius of the circle')
#declare arguments
parser.add_argument('foo')
parser.add_argument('-r','--radius', type = int, help='radius of the circle')
args = parser.parse_args('bar -r 30'.split())
print(args)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved