Lesson 29 of 30 · Mini Projects
Project: Simple Calculator
Build a calculator in Python step by step. Practise functions, return values, user input, loops and error handling, then extend it with your own features.
- 6 min read
- Beginner
- Reviewed
- How to split a program into small functions
- How to choose an action based on what the user types
- How to keep a program running until the user decides to stop
- How to handle every kind of bad input without crashing
What you will build
A calculator that runs in a loop. It asks for a number, an operator and another number, shows the answer and then asks again, until the user types q to quit. It must never crash, whatever the user types.
Plan
- Write a function that does the calculation.
- Read two numbers and an operator from the user.
- Show the result.
- Handle mistakes: text instead of a number, an unknown operator, dividing by zero.
- Repeat until the user quits.
Step 1: the calculation
Begin with the part that has nothing to do with input: a function that takes two numbers and an operator and returns the answer.
def calculate(a, operator, b):
if operator == "+":
return a + b
if operator == "-":
return a - b
if operator == "*":
return a * b
if operator == "/":
return a / b
print(calculate(6, "+", 7))
print(calculate(6, "-", 7))
print(calculate(6, "*", 7))
print(calculate(6, "/", 3))Because the function returns its result instead of printing it, you can test it with a few print lines before any other code exists. Testing each piece as you build it is a habit worth keeping.
Step 2: unknown operators
What does calculate(6, "^", 2) return? None of the conditions match, so the function reaches its end and returns None. A silent wrong answer is worse than an error. Make the problem loud with raise.
def calculate(a, operator, b):
if operator == "+":
return a + b
if operator == "-":
return a - b
if operator == "*":
return a * b
if operator == "/":
return a / b
raise ValueError(f"Unknown operator: {operator}")
try:
print(calculate(6, "^", 2))
except ValueError as error:
print("Error:", error)Step 3: read from the user
input() returns text, so convert the numbers. float() accepts both whole numbers and decimals.
def calculate(a, operator, b):
if operator == "+":
return a + b
if operator == "-":
return a - b
if operator == "*":
return a * b
if operator == "/":
return a / b
raise ValueError(f"Unknown operator: {operator}")
first = float(input("First number: "))
operator = input("Operator (+ - * /): ")
second = float(input("Second number: "))
print("Result:", calculate(first, operator, second))Step 4: three things that can go wrong
- The user types
abcfor a number:float()raises aValueError. - The user types an operator we do not support: our own
ValueError. - The user divides by zero: Python raises a
ZeroDivisionError.
One try block with two except blocks handles all three.
The finished calculator
def calculate(a, operator, b):
"""Return the result of applying operator to a and b."""
if operator == "+":
return a + b
if operator == "-":
return a - b
if operator == "*":
return a * b
if operator == "/":
return a / b
raise ValueError(f"unknown operator '{operator}'")
def main():
print("Simple calculator. Type q as the first number to quit.")
while True:
first = input("First number: ")
if first == "q":
print("Goodbye!")
break
operator = input("Operator (+ - * /): ")
second = input("Second number: ")
try:
result = calculate(float(first), operator, float(second))
except ValueError as error:
print("Error:", error)
continue
except ZeroDivisionError:
print("Error: cannot divide by zero")
continue
print(f"{first} {operator} {second} = {result}")
main()The Input box plays the part of a user who makes every possible mistake. Follow the output and match each line to the code:
6 * 7works and prints the answer.10 / 0is caught byexcept ZeroDivisionError.5 ^ 2is caught byexcept ValueError, with our own message.abc + 1is also caught byexcept ValueError, with Python's message.qends the loop.
After each error, continue jumps back to the top of the loop, so the calculator keeps running.
Why this structure is good
calculateknows nothing about input or printing. It could be reused in a website, a chatbot or a test without changing a line.mainhandles the conversation with the user. All theinputandprintcalls are in one place.- Errors are raised where they happen and handled where the user can be told.
Keeping calculation separate from input and output is one of the most valuable habits in programming.
Make it your own
- Add the power operator
**and the remainder operator%. - Round results to two decimal places.
- Keep a list of past calculations and show it when the user types
history. - Let the user type the whole sum on one line, such as
6 * 7, and usesplit()to separate the parts.
Without looking back, write the calculate function yourself.
# Write a function called calculate that takes a, operator and b. # It must RETURN the answer for the operators "+", "-", "*" and "/". # Do not change these lines. Output must be exactly: # 42 # 4 print(calculate(6, "*", 7)) print(calculate(9, "-", 5))
Why is it better for calculate() to return its result instead of printing it?
Summary
- Build the core logic first, as a function that returns a value.
- Test each piece before adding the next.
raisean error when your function receives something it cannot handle.- Use
while Truewithbreakfor a program that runs until the user quits. - Keep calculation separate from input and output.
One lesson left: where to go from here.
Finished reading? Tick it off to track your progress.