A script people run from a terminal takes flags. argparse builds that interface. In this editor there is no real argv, so you set sys.argv yourself.
Goal
Parse --city and --units, then print a kiosk line.
Fake argv, real parser
import argparse
import sys
sys.argv = ["kiosk", "--city", "Nairobi", "--units", "3"]
parser = argparse.ArgumentParser(description="Kiosk line")
parser.add_argument("--city", default="Nairobi")
parser.add_argument("--units", type=int, required=True)
args = parser.parse_args()
print(args.city, args.units)Wire it to a helper
import argparse
import sys
def line_total(units, price, tax=0.16):
return round(units * price * (1 + tax), 2)
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument("--city", default="Mombasa")
parser.add_argument("--units", type=int, default=1)
parser.add_argument("--price", type=float, default=10.5)
args = parser.parse_args(argv)
print(args.city, line_total(args.units, args.price))
if __name__ == "__main__":
main(["--city", "Nakuru", "--units", "4"])Passing argv into main makes the function testable without touching sys.argv.
Tip
On a laptop you would run python kiosk.py --city Nairobi --units 3. Here, pass a list to parse_args or set sys.argv.