← Intro to programming with Python

Mini project: a calculator that never crashes

Read two numbers and an operation, and handle every bad input kindly.

Start this lesson

A good program expects people to make mistakes. This calculator reads two numbers and an operation (+, -, * or /), and stays friendly no matter what: words instead of numbers, division by zero, or an operation it does not know. Each problem gets a clear message instead of a crash.

def calculate(a, op, b):
    if op == "+":
        return a + b
    if op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    return "Unknown operation"

Checking b == 0 first is another way to avoid a ZeroDivisionError. Sometimes an if is simpler than try / except.

Common mistake: forgetting the "none of the above" case. Always decide what happens when the input matches nothing you expected.