Building a Calculator in Python
Build a working calculator in Python step by step: read numbers with input, do the four operations, handle the divide-by-zero problem and loop for more sums. Beginner-friendly with runnable code, a full program and a quiz.
Key takeaways
- Python does maths with + - * / and you can store the answer in a variable
- input() always returns text, so use float() to turn a typed number into a real number
- if / elif / else lets the calculator choose which operation to do
- Dividing by zero crashes a program, so you must check for it before dividing
- A while loop lets the user do many calculations without restarting the program
A calculator you build yourself
Every phone has a calculator app, and somebody had to program it. In this lesson you'll build your own — first a simple version, then a full one that lets you keep doing sums until you're finished. Along the way you'll practise the maths operators, reading input, making decisions, and looping. It's a perfect first real project.
If you've met variables and basic input and output, you have everything you need. Let's go.
The maths operators
Python knows arithmetic out of the box. Here are the four you'll use most:
print(8 + 3) # addition -> 11
print(8 - 3) # subtraction -> 5
print(8 * 3) # multiplication-> 24
print(8 / 3) # division -> 2.6666666666666665
Two things to notice. Multiplication uses * (a star), not x. And division with / gives a decimal answer, even when it divides evenly — 6 / 2 is 3.0, not 3. You can store any result in a variable:
total = 100 + 50
print(total) # 150
Reading numbers from the user
A calculator is useless if it can only work with numbers you typed into the code. We want the user to supply them. The input() function asks a question and gives back whatever they type — but always as text:
typed = input("Enter a number: ")
print(typed + typed)
If you typed 5, that surprisingly prints 55, not 10! That's because typed is the string "5", and adding strings glues them together. To do real maths we must convert the text to a number with float():
number = float(input("Enter a number: "))
print(number + number) # now typing 5 gives 10.0
float() turns "5" into the number 5.0. We use float (rather than int) so the calculator handles decimals like 3.5 too.
Choosing an operation with if / elif / else
A real calculator lets you pick +, -, * or /. We ask which one and use if / elif / else to decide what to do:
a = float(input("First number: "))
op = input("Operation (+ - * /): ")
b = float(input("Second number: "))
if op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(a / b)
else:
print("Unknown operation.")
The program checks the symbol the user typed and runs the matching line. The final else catches anything that isn't one of the four operators, so a typo doesn't silently do nothing. If you'd like a refresher, see making decisions with if.
The divide-by-zero trap
There's one sum that breaks maths itself: dividing by zero. In Python it doesn't give a wrong answer — it crashes your whole program with a ZeroDivisionError. We must guard against it:
if op == "/":
if b == 0:
print("Cannot divide by zero!")
else:
print(a / b)
The inner if b == 0 checks the divisor before dividing. If the second number is zero, we print a polite message instead of crashing. Always protect division this way.
Worked example: the full calculator
Now we combine everything — and wrap it in a while loop so the user can do as many calculations as they like, then quit when they're done.
def calculate(a, op, b):
"""Return the result of a op b, or an error message string."""
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
if b == 0:
return "Error: cannot divide by zero"
return a / b
else:
return "Error: unknown operation"
def run_calculator():
print("Simple Calculator — type q at any time to quit.")
while True:
first = input("\nFirst number: ")
if first == "q":
break
a = float(first)
op = input("Operation (+ - * /): ")
b = float(input("Second number: "))
result = calculate(a, op, b)
print(f"{a} {op} {b} = {result}")
print("Goodbye!")
run_calculator()
How it works:
calculate(a, op, b)is a function that does one job: it takes two numbers and an operator and returns the answer. Keeping the maths in its own function makes the program tidy and testable. Notice the divide-by-zero check returns a message instead of crashing.run_calculatorholds the loop.while True:repeats forever until webreak.- Before converting, we check
if first == "q":so the user can quit by typingq. Putting the check first means we never try tofloat("q"), which would crash. - Each pass reads the operator and second number, calls
calculate, and prints a neat line like8.0 * 3.0 = 24.0.
Run it and you've got a real, reusable calculator. Type a few sums, then q to leave.
Try it yourself
Make your calculator smarter:
- Add a power operation. In Python,
a bmeans "a to the power of b" (so2 3is 8). Add anelif op == "**":branch. - Add a remainder operation using
%(so7 % 2is 1). - Keep a running history: each time you calculate, append the result line to a list, and when the user types
q, print the whole history before saying goodbye. - Challenge: protect the program from non-number input by wrapping
float(...)in atry/except ValueErrorso a typo shows "Please type a number" instead of crashing.
When your calculator works, see how the same return-based thinking powers other programs in functions that return values.
Quick quiz
Test yourself and earn XP
What does the * symbol do in Python?
* is the multiplication operator. + adds, - subtracts and / divides.
Why do we wrap input() in float()?
input() always returns a string. float() converts "7.5" into the number 7.5 so + - * / work correctly.
What does this print? ``` a = float("6") b = float("2") print(a / b) ```
Dividing two floats gives a float, so 6.0 / 2.0 is 3.0.
What happens if a program tries to compute 5 / 0?
Division by zero is undefined, so Python raises a ZeroDivisionError. You must check for a zero divisor first.
Which structure lets the user do many calculations in a row without restarting?
A while loop repeats the calculator steps until the user chooses to stop.
FAQ
A single slash / does normal division and always gives a decimal: 7 / 2 is 3.5. A double slash // does floor division, which throws away the fractional part: 7 // 2 is 3. There is also %, the modulo operator, which gives the remainder: 7 % 2 is 1. For a normal calculator you want the single / so you get exact decimal answers.
float("hello") cannot be turned into a number, so Python raises a ValueError and stops. Real apps prevent this by wrapping the conversion in a try / except ValueError block, or by checking the input first. For a beginner calculator it is fine to assume numbers are typed, but catching the error is a great next step.
Keep exploring
More in Coding