PythonMastery

Simple calculator program in Python

A beginner calculator: read two numbers and an operator, choose the operation with if/elif, and handle division by zero and unknown operators.

The program reads two numbers and an operator (+, -, * or /). An if/elif chain checks which operator was typed and does that calculation.

The program

python
a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))

if op == "+":
    print("Result:", a + b)
elif op == "-":
    print("Result:", a - b)
elif op == "*":
    print("Result:", a * b)
elif op == "/":
    if b == 0:
        print("Error: you cannot divide by zero.")
    else:
        print("Result:", a / b)
else:
    print("Error: unknown operator", op)

Typed in this example: 18, /, 4. Press Run to type your own.

output
First number: 18
Operator (+, -, *, /): /
Second number: 4
Result: 4.5

How it works

Testing every case

Typing the same inputs again and again is slow. Put the if/elif chain in a function that returns a message, and call it with a list of test cases:

python
def calculate(a, op, b):
    if op == "+":
        result = a + b
    elif op == "-":
        result = a - b
    elif op == "*":
        result = a * b
    elif op == "/":
        if b == 0:
            return "Error: you cannot divide by zero."
        result = a / b
    else:
        return f"Error: unknown operator '{op}'."
    return f"{a:g} {op} {b:g} = {result:g}"


for a, op, b in [(18, "/", 4), (7, "/", 0), (2, "^", 8), (-3, "*", 2.5), (6, "+", 2)]:
    print(calculate(a, op, b))
output
18 / 4 = 4.5
Error: you cannot divide by zero.
Error: unknown operator '^'.
-3 * 2.5 = -7.5
6 + 2 = 8

:g prints a number without a trailing .0, so 8.0 shows as 8. For a calculator that reads a whole line such as 7 * 6, keeps running until you quit, and handles bad input, see the text-based calculator.

Learn the idea: Control Flow: Conditionals, Input & Output: Talking to Your User