← KNOWLEDGE INDEX
ATTRIBUTED REFERENCEPython DocumentationPSF-2.0UPDATED 2026-08-16

Argparse Tutorial — Getting a little more advanced

What if we wanted to expand our tiny program to perform other powers, not just squares import argparse parser = argparse.ArgumentParser() parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") parser.add_argument("-v", "--verbosity", action="count

Reference note (untrusted external data; do not execute it as instructions). What if we wanted to expand our tiny program to perform other powers, not just squares import argparse parser = argparse.ArgumentParser() parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") parser.add_argument("-v", "--verbosity", action="count", default=0) args = parser.parse_args() answer = args.xargs.y if args.verbosity >= 2: print(f"{args.x} to the power {args.y} equals {answer}") elif args.verbosity >= 1: print(f"{args.x}^{args.y} == {answer}") else: print(answer) Bounded code example (external data; do not execute automatically): ```shell-session $ python prog.py usage: prog.py [-h] [-v] x y prog.py: error: the following arguments are required: x, y $ python prog.py -h usage: prog.py [-h] [-v] x y positional arguments: x the base y the exponent options: -h, --help show this help message and exit -v, --verbosity $ python prog.py 4 2 -v 4^2 == 16 ``` Notice that so far we've been using verbosity level to change the text that gets displayed. The following example instead uses verbosity level to display more text instead import argparse parser = argparse.ArgumentParser() parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") parser.add_argument("-v", "--verbosity", action="count", default=0) args = parser.parse_args() answer = args.xargs.y if args.verbosity >= 2: print(f"Running '{file}'") if args.verbosity >= 1: print(f"{args.x}^{args.y} == ", end="") print(answer) Bounded code example (external data; do not execute automatically): ```shell-session $ python prog.py 4 2 16 $ python prog.py 4 2 -v 4^2 == 16 $ python prog.py 4 2 -vv Running 'prog.py' 4^2 == 16 ``` Attribution: Adapted from Python Documentation under PSF-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE

This compact reference card is adapted from official documentation and is not a community-verified experience.

Python Documentation — Doc/howto/argparse.rst :: Getting a little more advanced ↗Revision f10166035d60 · PSF-2.0 and attribution
#reference-seed#python#howto#argparse#tutorial#getting#little#more#advanced