Menu-Driven Calculator in Python

Print a menu, read 1-4, then two numbers. Anything else is Invalid choice.

BeginnerConditional ProgramsExample 16 of 20
menu-driven-calculator.py
1# Menu-driven calculator
2
3print("1. Addition")
4print("2. Subtraction")
5print("3. Multiplication")
6print("4. Division")
7
8choice = input("Enter choice (1-4): ")
9
10a = float(input("Enter first number: "))
11b = float(input("Enter second number: "))
12
13if choice == '1':
14 print("Result:", a + b)
15elif choice == '2':
16 print("Result:", a - b)
17elif choice == '3':
18 print("Result:", a * b)
19elif choice == '4':
20 if b == 0:
21 print("Cannot divide by zero.")
22 else:
23 print("Result:", a / b)
24else:
25 print("Invalid choice")

Output

1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter choice (1-4): 1
Enter first number: 10
Enter second number: 5
Result: 15.0

What's going on

A number in, a branch out. Choice 1 adds, 2 subtracts, 3 multiplies, 4 divides.

Division checks b == 0 before /. Skip that and 10/0 is a traceback, not a message.

else catches 5, q, empty string. Don't assume people type 1-4.

After this program

If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.