The program reads two numbers and an operator (+, -, * or /). An if/elif chain checks which operator was typed and does that calculation.
The program
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.
First number: 18 Operator (+, -, *, /): / Second number: 4 Result: 4.5
How it works
opstays a string, so the program compares it with"+","-"and so on.- Python checks the conditions from top to bottom and runs only the first branch that matches.
- Dividing by zero would stop the program with a
ZeroDivisionError, so the/branch checksb == 0first. - The final
elsecatches anything else the user types, such as^orx. - Because both numbers are floats,
6 + 2prints8.0.
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:
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))
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.