PythonMastery

Menu driven program in Python

A shopping list program with a menu: add, show, remove and quit. A while loop shows the menu again after each choice until the user quits.

A menu driven program shows a list of choices, does what the user picks, and then shows the menu again. A while True loop keeps it running until the user chooses to quit.

The program

python
shopping = []

while True:
    print("Menu: 1 Add  2 Show  3 Remove  4 Quit")
    choice = input("Your choice: ").strip()

    if choice == "1":
        item = input("Item to add: ").strip()
        if item:
            shopping.append(item)
            print(f"Added {item}.")
        else:
            print("Nothing added.")
    elif choice == "2":
        if shopping:
            for number, item in enumerate(shopping, start=1):
                print(f"  {number}. {item}")
        else:
            print("The list is empty.")
    elif choice == "3":
        item = input("Item to remove: ").strip()
        if item in shopping:
            shopping.remove(item)
            print(f"Removed {item}.")
        else:
            print(f"{item} is not on the list.")
    elif choice == "4":
        print("Goodbye.")
        break
    else:
        print("Please choose 1, 2, 3 or 4.")

Typed in this example: 1, milk, 1, bread, 1, eggs, 3, butter, 3, bread, 5, 2, 4. Press Run to type your own.

output
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 1
Item to add: milk
Added milk.
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 1
Item to add: bread
Added bread.
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 1
Item to add: eggs
Added eggs.
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 3
Item to remove: butter
butter is not on the list.
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 3
Item to remove: bread
Removed bread.
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 5
Please choose 1, 2, 3 or 4.
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 2
  1. milk
  2. eggs
Menu: 1 Add  2 Show  3 Remove  4 Quit
Your choice: 4
Goodbye.

How it works

Another way: match

From Python 3.10, a match statement can replace the if/elif chain. Each case is one menu choice, and case _: catches everything else:

python
def handle(choice):
    match choice:
        case "1":
            return "add"
        case "2":
            return "show"
        case "3":
            return "remove"
        case "4":
            return "quit"
        case _:
            return "unknown choice"


for choice in ["2", "4", "9"]:
    print(choice, "->", handle(choice))
output
2 -> show
4 -> quit
9 -> unknown choice

The match statement program shows more of what match can do. The to-do list project builds a bigger menu program that also saves the list to a file.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Lists & Sequences, Control Flow: Conditionals