Menu-Driven Programs in Python
What is a Menu-Driven Program?
A menu-driven program is an interactive program that allows users to choose from a list offered in a menu. Based on the user’s choice, the program performs certain tasks. They suit applications in which users repeatedly interact with the program.
Features of a Menu-Driven Program
1. Menu Display:
- The program shows a list of options clearly.
- Example:
1. Add
2. Subtract
3. Multiply
4. Exit
2. User Input:
- The program reads the user’s choice using
input().
3. Conditional Execution:
- Based on the user’s input, the program uses conditional statements (
if-elif-else) to perform specific actions.
4. Repetition:
- The menu will continue to be shown each time using a
whileloop until the user wants to exit.
5. Error Handling:
- The program handles wrong inputs such as typing a letter instead of a number very presciently.
Basic Structure of a Menu-Driven Program
Here’s the skeleton structure of a menu-driven program:
while True:
# Step 1: Display the menu
print("1. Option A")
print("2. Option B")
print("3. Exit")
# Step 2: Take user input
choice = input("Enter your choice: ")
# Step 3: Perform actions based on the choice
if choice == '1':
print("You chose Option A.")
elif choice == '2':
print("You chose Option B.")
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice! Please try again.")
Explanation:
- Loop: Ensures the program keeps displaying the menu until the user exits.
- Conditional Logic: Matches the user’s choice to predefined actions.
- Error Handling: Handles invalid choices by displaying a message.
Example 1: A Menu-Driven Calculator
This program lets users perform basic arithmetic operations like addition, subtraction, multiplication, and division.
def display_menu():
print("\n--- Calculator Menu ---")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error! Division by zero."
return a / b
while True:
display_menu()
choice = input("Enter your choice (1-5): ")
if choice == '5':
print("Exiting the program. Goodbye!")
break
elif choice in ['1', '2', '3', '4']:
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
except ValueError:
print("Invalid input! Please enter numeric values.")
continue
if choice == '1':
print(f"The result is: {add(num1, num2)}")
elif choice == '2':
print(f"The result is: {subtract(num1, num2)}")
elif choice == '3':
print(f"The result is: {multiply(num1, num2)}")
elif choice == '4':
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid choice! Please choose a valid option.")
Output and Explanation
Case 1: Addition
--- Calculator Menu ---
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 1
Enter the first number: 10
Enter the second number: 20
The result is: 30.0
- The user selects 1 (Add).
- Inputs
10and20are passed to theadd()function, which returns30.
Case 2: Division by Zero
--- Calculator Menu ---
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 4
Enter the first number: 10
Enter the second number: 0
The result is: Error! Division by zero.
- The user selects 4 (Divide).
- Since dividing by zero is not allowed, the
divide()function handles this error gracefully.
Case 3: Invalid Choice
--- Calculator Menu ---
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 6
Invalid choice! Please choose a valid option.
- The user enters an invalid choice (
6), so the program displays a message and re-displays the menu.
Example 2: A Menu-Driven To-Do List
This program lets users manage a to-do list.
todo_list = []
def display_menu():
print("\n--- To-Do List Menu ---")
print("1. Add Task")
print("2. View Tasks")
print("3. Remove Task")
print("4. Exit")
while True:
display_menu()
choice = input("Enter your choice (1-4): ")
if choice == '1':
task = input("Enter the task to add: ")
todo_list.append(task)
print(f"Task '{task}' added.")
elif choice == '2':
if not todo_list:
print("No tasks in the list.")
else:
print("Your Tasks:")
for i, task in enumerate(todo_list, start=1):
print(f"{i}. {task}")
elif choice == '3':
if not todo_list:
print("No tasks to remove.")
else:
for i, task in enumerate(todo_list, start=1):
print(f"{i}. {task}")
try:
remove_index = int(input("Enter the task number to remove: "))
removed_task = todo_list.pop(remove_index - 1)
print(f"Task '{removed_task}' removed.")
except (ValueError, IndexError):
print("Invalid task number!")
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice! Please choose a valid option.")
Output and Explanation
Case 1: Adding Tasks
--- To-Do List Menu ---
1. Add Task
2. View Tasks
3. Remove Task
4. Exit
Enter your choice (1-4): 1
Enter the task to add: Buy groceries
Task 'Buy groceries' added.
- The user selects 1 (Add Task) and enters a task.
- The task is appended to the
todo_list.
Case 2: Viewing Tasks
--- To-Do List Menu ---
1. Add Task
2. View Tasks
3. Remove Task
4. Exit
Enter your choice (1-4): 2
Your Tasks:
1. Buy groceries
- The user selects 2 (View Tasks).
- The program iterates through
todo_listand displays each task with an index.
Case 3: Removing a Task
--- To-Do List Menu ---
1. Add Task
2. View Tasks
3. Remove Task
4. Exit
Enter your choice (1-4): 3
1. Buy groceries
Enter the task number to remove: 1
Task 'Buy groceries' removed.
- The user selects 3 (Remove Task) and provides the task number.
- The program removes the corresponding task using
pop().
Case 4: No Tasks to Remove
--- To-Do List Menu ---
1. Add Task
2. View Tasks
3. Remove Task
4. Exit
Enter your choice (1-4): 3
No tasks to remove.
- If
todo_listis empty, the program displays an appropriate message.
Advanced Features
- Persistent Storage: Save tasks to a file so that they are available even after restarting the program.
- Graphical Menu: Use a GUI framework like
tkinterfor a visual interface. - Submenus: Add submenus for advanced functionality.