Python Practice › If-Else Programs › Program 63
Calculator with an operator
Write a Python program that accepts two numbers and an operator (+, -, *, /) and prints the result.
Input
30, 45, +
Output
30 + 45 = 75 30 * 45 = 1350 9 / 0 = cannot divide by zero 2 % 3 = unknown operator
Approach
- Choose the operation with if-elif.
- Guard against division by zero.
Solution
def calculate(a, b, op): if op == "+": return a + b elif op == "-": return a - b elif op == "*": return a * b elif op == "/": if b == 0: return "cannot divide by zero" return a / b else: return "unknown operator" for a, b, op in [(30, 45, "+"), (30, 45, "*"), (9, 0, "/"), (2, 3, "%")]: print(a, op, b, "=", calculate(a, b, op))Output
30 + 45 = 75 30 * 45 = 1350 9 / 0 = cannot divide by zero 2 % 3 = unknown operator
Line by line
Lines 8-11
A nested if checks for zero before dividing.
Lines 12-13
Any other symbol gets a clear message.
Learn the concept
New to this topic? Read the lesson, then come back.