Calculator with an operator

MediumIf-Else Programs · 63 of 64

Write a Python program that accepts two numbers and an operator (+, -, *, /) and prints the result.

Advertisement
Input
30, 45, +
Output
30 + 45 = 75
30 * 45 = 1350
9 / 0 = cannot divide by zero
2 % 3 = unknown operator

Approach

  1. Choose the operation with if-elif.
  2. Guard against division by zero.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs