Table of Contents
- What is a Menu Driven Program in Python?
- The 3 Core Components You Need to Know
- Step-by-Step Example: Building a Simple Interactive Calculator
- Upgrading Your Menu: Error Handling and Edge Cases
- How to get a daily menu with a Python script
- Real-World Use Cases for CLI Menus
- Menu driven programs in Python: common questions
- Conclusion
A menu driven program in Python prints a numbered list of choices inside a while True loop, reads the choice with input(), runs the matching code with if and elif, and stops with break when the user picks Exit. That is the whole pattern; everything else is what each choice does.
Below you will build a calculator menu and see exactly what it prints, make it survive bad input, and then write a script that prints today's menu, from a dictionary or from a file, and turn it into a menu driven canteen program.
Real applications interact with the user. Think about an ATM screen, a restaurant ordering kiosk, or a classic text-based RPG game. They don't require the user to edit code. They all rely on the exact same core concept: displaying a list of choices, waiting for a command, and executing a specific task based on that command.
If you want to stop writing static, one-time-use scripts and start building interactive applications, you need to learn how to structure a menu driven program in Python. In this guide, we will break down the exact logic, loops, and syntax you need to build dynamic, unbreakable command-line interfaces from scratch.
What is a Menu Driven Program in Python?
A menu-driven program is exactly what it sounds like. It is a script that continuously displays a list of options (a menu) to the user. It waits for them to type in their choice, runs the specific block of code associated with that choice, and then loops back to the beginning to ask them what they want to do next.
Almost every command-line interface (CLI) tool relies on this architecture. The core logic is built on three pillars:
- A continuous loop that keeps the program alive.
- A prompt that captures the user's input.
- A decision tree that figures out what to do with that input.
While you can write all your logic directly inside the menu, the best way to keep your code clean is to split your actions into reusable blocks. Understanding the advantages of functions in Python is highly recommended before you start building massive menus, as it keeps your main loop from becoming an unreadable mess.
The 3 Core Components You Need to Know
Before we write the actual code, you need to understand the three specific Python features that make a menu work.
1. The Infinite while Loop
Normally, a Python script runs from top to bottom and then stops completely. To build a menu, we don't want the program to stop until the user explicitly tells it to. We achieve this using while True:. Because "True" is always true, this loop will run forever, keeping our menu alive on the screen.
2. if-elif-else Control Flow
Once the user types a number (like "1" to Add or "2" to Subtract), the program needs to route that choice to the correct action. We use conditional statements to map inputs to actions. If you want to dive deeper into how conditionals evaluate data, check out the official Python Documentation on Control Flow.
3. The break Statement
If a while True loop runs forever, how does the user ever close the app? We give them a "Quit" option. When they select it, we execute a break statement, which instantly kills the loop and safely shuts down the program.
Step-by-Step Example: Building a Simple Interactive Calculator
Let's put the theory into practice. We are going to build a text-based calculator. The user will see a menu, pick a math operation, input two numbers, get the result, and then see the menu again.
Here is the complete, working code, and underneath it what one run looks like: add 8 and 2, type a choice that does not exist, then exit.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def divide(x, y):
if y == 0:
return "Error: Cannot divide by zero!"
return x / y
while True:
# Step 1: show the menu
print("\n--- Main Menu ---")
print("1. Add Numbers")
print("2. Subtract Numbers")
print("3. Divide Numbers")
print("4. Exit Program")
# Step 2: read the choice
choice = input("Enter your choice (1-4): ")
# Step 3: act on it
if choice == "4":
print("Exiting the program. Goodbye!")
break # leaves the while loop
if choice in ("1", "2", "3"):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == "1":
print(f"Result: {num1} + {num2} = {add(num1, num2)}")
elif choice == "2":
print(f"Result: {num1} - {num2} = {subtract(num1, num2)}")
else:
print(f"Result: {num1} / {num2} = {divide(num1, num2)}")
else:
# Step 4: anything else is a bad choice
print("Invalid input. Please enter a number between 1 and 4.")
--- Main Menu ---
1. Add Numbers
2. Subtract Numbers
3. Divide Numbers
4. Exit Program
Enter your choice (1-4): 1
Enter first number: 8
Enter second number: 2
Result: 8.0 + 2.0 = 10.0
--- Main Menu ---
1. Add Numbers
2. Subtract Numbers
3. Divide Numbers
4. Exit Program
Enter your choice (1-4): 5
Invalid input. Please enter a number between 1 and 4.
--- Main Menu ---
1. Add Numbers
2. Subtract Numbers
3. Divide Numbers
4. Exit Program
Enter your choice (1-4): 4
Exiting the program. Goodbye!
Notice how clean the main loop is? We isolated the math logic into functions at the top, leaving the while True loop to handle nothing but routing traffic. Also, if you want to upgrade option 3 to handle advanced division methods, brushing up on what is floor division in Python is a great next step.
Upgrading Your Menu: Error Handling and Edge Cases
The calculator above works great if the user follows the rules. But users never follow the rules.
What happens if the menu asks for a number, and the user accidentally types the letter "A"? The program hits float(input()), panics because "A" is not a number, and crashes entirely. A massive wall of red error text appears, and the app closes.
To build a professional menu driven program in Python, you have to make it unbreakable using try-except blocks.
Instead of letting the program crash, put the conversion in a small function that tries, catches the ValueError, and asks again. Use read_number() wherever the menu needs a number:
That one guard is just the beginning of what try and except can do. Our full guide to exception handling in Python covers else, finally, raise, and the habits that keep real programs alive when users get creative.
def read_number(prompt):
while True: # keep asking until the input is a number
try:
return float(input(prompt))
except ValueError:
print("That is not a valid number! Please try again.")
num = read_number("Enter first number: ")
print("Got", num)
Enter first number: A
That is not a valid number! Please try again.
Enter first number: 12
Got 12.0
Learning how to anticipate user mistakes is a massive part of software engineering. For advanced techniques on stopping crashes before they happen, look into comprehensive Python Error Handling strategies.
Bonus UX Upgrade: By default, your menu will just keep printing down the terminal screen, creating a massive, cluttered log. You can make it look like a real, static application interface by importing the os module and clearing the screen at the start of every loop using os.system('cls' if os.name == 'nt' else 'clear').
How to get a daily menu with a Python script
A daily menu script answers one question, what is on today, and it needs two things: the menu for each day of the week, and today's day name. Python's datetime module gives the day name with date.today().strftime("%A"), and a dictionary keyed by day name holds the menu.
from datetime import date
WEEKLY_MENU = {
"Monday": ["Veg pulao", "Dal tadka", "Salad"],
"Tuesday": ["Rajma chawal", "Jeera aloo", "Curd"],
"Wednesday": ["Pasta", "Garlic bread", "Fruit"],
"Thursday": ["Chole", "Rice", "Pickle"],
"Friday": ["Paneer wrap", "Soup", "Brownie"],
"Saturday": ["Idli", "Sambar", "Chutney"],
"Sunday": ["Poha", "Masala chai"],
}
today = date.today().strftime("%A") # e.g. "Wednesday"
print(f"Menu for {today}:")
for dish in WEEKLY_MENU[today]:
print(" -", dish)
Menu for Wednesday:
- Pasta
- Garlic bread
- Fruit
The output above is from a Wednesday; run it on another day and you get that day's dishes. If a canteen, a school or a family keeps the menu in a file, read it from there instead, so changing the menu never means editing code. JSON suits this because Python reads it straight into a dictionary:
import json
from datetime import date, timedelta
# In real use the file already exists; this line only creates a small one to read.
with open("menu.json", "w") as f:
json.dump({"Monday": ["Veg pulao", "Dal"], "Tuesday": ["Rajma chawal"],
"Wednesday": ["Pasta", "Fruit"], "Thursday": ["Chole", "Rice"],
"Friday": ["Paneer wrap"], "Saturday": ["Idli", "Sambar"],
"Sunday": ["Poha"]}, f)
def menu_for(day):
with open("menu.json") as f:
menu = json.load(f)
return menu.get(day.strftime("%A"), ["No menu published for this day"])
wednesday = date(2026, 9, 23)
for offset in range(3):
day = wednesday + timedelta(days=offset)
print(day.strftime("%a %d %b"), "->", ", ".join(menu_for(day)))
Wed 23 Sep -> Pasta, Fruit
Thu 24 Sep -> Chole, Rice
Fri 25 Sep -> Paneer wrap
Now combine the two ideas from this guide: a menu driven program whose choices show the whole week or one chosen day.
from datetime import date
WEEKLY_MENU = {
"Monday": ["Veg pulao", "Dal"], "Tuesday": ["Rajma chawal"],
"Wednesday": ["Pasta", "Fruit"], "Thursday": ["Chole", "Rice"],
"Friday": ["Paneer wrap", "Soup"], "Saturday": ["Idli", "Sambar"],
"Sunday": ["Poha"],
}
def show(day):
print(f"{day}: " + ", ".join(WEEKLY_MENU[day]))
while True:
print("\n1. Show the whole week 2. Pick a day 3. Quit")
choice = input("Choice: ")
if choice == "1":
for day in WEEKLY_MENU:
show(day)
elif choice == "2":
day = input("Which day? ").strip().capitalize()
if day in WEEKLY_MENU:
show(day)
else:
print("Please type a day name, for example Monday")
elif choice == "3":
print("Bye!")
break
else:
print("Choose 1, 2 or 3")
1. Show the whole week 2. Pick a day 3. Quit
Choice: 1
Monday: Veg pulao, Dal
Tuesday: Rajma chawal
Wednesday: Pasta, Fruit
Thursday: Chole, Rice
Friday: Paneer wrap, Soup
Saturday: Idli, Sambar
Sunday: Poha
1. Show the whole week 2. Pick a day 3. Quit
Choice: 2
Which day? Friday
Friday: Paneer wrap, Soup
1. Show the whole week 2. Pick a day 3. Quit
Choice: 3
Bye!
If the menu is only published on a website, the script first has to download the page (with urllib.request from the standard library, or the requests package) and then pick the dishes out of the HTML. Check that the site allows it, and use a JSON feed or a downloadable file if the site offers one; it is far more reliable than scraping a page whose layout can change.
Real-World Use Cases for CLI Menus
Why bother learning this? Because command-line menus are everywhere in backend development, system administration, and data science.
Database Management (CRUD Apps)
Imagine building an employee directory. Your menu options would be: 1. Add Employee, 2. View All Employees, 3. Update Salary, 4. Delete Employee. When the user makes a choice, your script reads and writes to a CSV or text file. Understanding file types in Python is the key to hooking up a menu to a persistent database.
Task Automation Hubs
If you write a lot of Python scripts, maybe one to scrape a website, one to organize your desktop folders, and one to send an automated email, you can build a single menu-driven program to act as a central hub. You just launch your hub, press a number, and the designated bot goes to work.
Menu driven programs in Python: common questions
A program that shows the user a numbered list of options, waits for a choice, runs the code for that choice and then shows the menu again, until the user chooses to exit. It is built from a while True loop, input(), if/elif and break.
Print the options inside while True:, read the choice with choice = input("Choice: "), compare it with if choice == "1": and so on, and call break on the Exit option. Put each action in its own function so the loop stays short.
Store the menu in a dictionary keyed by day name, or in a JSON file, and look up date.today().strftime("%A"). The daily menu section above has three working versions with their output.
Wrap the conversion in try/except ValueError inside a loop, as in read_number() above, so bad input prints a message and asks again instead of ending the program.
Yes, from Python 3.10. match choice: with case "1":, case "2": and case _: for anything else reads neatly for long menus. if-elif works on every Python 3 version.
Write one function per operation, show them as numbered choices, read two numbers for the chosen operation and print the result, looping until the user exits. The calculator at the top of this guide does exactly that; add multiply as a fourth operation for practice.
Conclusion
Mastering the menu-driven architecture is the crucial stepping stone between writing basic practice scripts and building actual, usable software. Once you understand the while True loop and conditional routing, you can build practically anything.
Don't just read the code above. Copy it into your editor and break it. Add an option for multiplication. Change it from a calculator into a daily to-do list tracker. The fastest way to learn is to build.
Learn Python live, with a teacher reading your code
Menus are where beginners first build something that feels like an app; our students go on from here to files, classes and their own projects. Ages 9 to 12: Python and AI for Kids. Ages 13 to 18: Python for Teens. College students and adults: Python Masterclass. The first class is a free demo, so you can see how it is taught before you decide.