Velamuvi AIAcademy

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
In this lesson you will learn
  • 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

  1. Write a function that does the calculation.
  2. Read two numbers and an operator from the user.
  3. Show the result.
  4. Handle mistakes: text instead of a number, an unknown operator, dividing by zero.
  5. 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.

Try it yourselfPython
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.

Try it yourselfPython
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.

Try it yourselfPython
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 abc for a number: float() raises a ValueError.
  • 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

Try it yourselfPython
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:

  1. 6 * 7 works and prints the answer.
  2. 10 / 0 is caught by except ZeroDivisionError.
  3. 5 ^ 2 is caught by except ValueError, with our own message.
  4. abc + 1 is also caught by except ValueError, with Python's message.
  5. q ends the loop.

After each error, continue jumps back to the top of the loop, so the calculator keeps running.

Why this structure is good

  • calculate knows nothing about input or printing. It could be reused in a website, a chatbot or a test without changing a line.
  • main handles the conversation with the user. All the input and print calls 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 use split() to separate the parts.
Practice exercise

Without looking back, write the calculate function yourself.

Your solutionPython
# 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))
Knowledge check

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.
  • raise an error when your function receives something it cannot handle.
  • Use while True with break for 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.