Home / Python / Example programs / Useful mini-programs

Python program: A simple calculator

A calculator that applies + − × ÷ to two numbers, with error handling.

The code

def calculate(a, op, b):
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op in ("*", "x"):
        return a * b
    if op == "/":
        if b == 0:
            raise ZeroDivisionError("cannot divide by zero")
        return a / b
    raise ValueError(f"unknown operator {op!r}")

for expr in ["12 + 30", "7 x 6", "9 / 0", "5 ^ 2", "10 / 4"]:
    a, op, b = expr.split()
    try:
        print(expr, "=", calculate(float(a), op, float(b)))
    except (ZeroDivisionError, ValueError) as e:
        print(expr, "->", e)

Output

12 + 30 = 42.0
7 x 6 = 42.0
9 / 0 -> cannot divide by zero
5 ^ 2 -> unknown operator '^'
10 / 4 = 2.5

How it works

One function, one branch per operator, and errors raised for bad input. The caller catches them so the program keeps going. To make it interactive, read each expression with input() in the playground.

Python features used

Learn the ideas behind it in the free lesson Errors & Debugging.