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
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.
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
- Each choice is compared as text (
"1", not1).input()always returns a string, so there is no need to convert it, and a typed letter cannot cause aValueError. - The
elseat the end catches every answer that is not on the menu, such as5, and the loop shows the menu again. breakis the only way out ofwhile True. It runs only for choice 4.shopping.remove(item)raises aValueErrorif the item is not in the list, so the program checksitem in shoppingfirst.enumerate(shopping, start=1)numbers the items from 1 instead of 0.
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:
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))
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.