Menu-Driven Calculator

A simple text-based calculator using a menu and conditional logic.

BeginnerTopic: Conditional Programs
Back

Python Menu-Driven Calculator Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Menu-driven calculator

print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = input("Enter choice (1-4): ")

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

if choice == '1':
    print("Result:", a + b)
elif choice == '2':
    print("Result:", a - b)
elif choice == '3':
    print("Result:", a * b)
elif choice == '4':
    if b == 0:
        print("Cannot divide by zero.")
    else:
        print("Result:", a / b)
else:
    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

Understanding Menu-Driven Calculator

This showcases a classic menu-driven program controlled by user input.

We use a chain of elif to dispatch different arithmetic operations and guard against division by zero.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents