Learn AI
~50 minIn progress

Phase 1 · Programming Fundamentals

Project: Calculator

Build a CLI calculator with functions, a looped menu, and solid input validation.

~50 min4 sections2 exercisesQuiz · pass 4/5
On this page
  1. 01Project spec
  2. 02Step 1 — operation functions
  3. 03Step 2 — safe number input
  4. 04Step 3 — menu loop
  5. 05Ship the calculator
  6. 06Try It
  7. 07Quiz

Project spec

Build a calculator that:

  • Shows a menu: add, subtract, multiply, divide, quit
  • Asks for two numbers for each operation
  • Prints the result
  • Rejects invalid numbers and division by zero without crashing
  • Loops until the user quits
Sample session
=== Calculator ===
1) add
2) subtract
3) multiply
4) divide
5) quit
Choose: 1
a: 12
b: 5
Result: 17.0

Step 1 — operation functions

Write one function per operation. Keep them tiny and testable.

divide should guard against b == 0 (return None or raise a clear error you catch later).

Core operations
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return None
    return a / b

print(add(2, 3), divide(10, 2), divide(10, 0))

Returning None for illegal divide keeps the UI layer in charge of the message.

Step 2 — safe number input

Wrap float(input(...)) in try/except ValueError and keep asking until the user types a valid number.

This helper removes duplication from every menu action.

read_number helper
def read_number(prompt):
    while True:
        raw = input(prompt)
        try:
            return float(raw)
        except ValueError:
            print("Please enter a valid number.")

# In Try It, call read_number once or twice to test

Practice

Ship the calculator

Assemble the full app: helpers + operations + menu loop. Support all four operations, validate numbers, handle divide-by-zero, and quit cleanly. Extra credit: remember the last result and allow using it as the next a via typing "ans".

challenge starter
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return None
    return a / b

def read_number(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please enter a valid number.")

# TODO: menu loop wiring everything together

Interactive

Try It in the browser

Powered by Pyodide

Implement add/subtract/multiply/divide as above. Print results for (8,2) on all four ops, and show that divide(8,0) is None.

Output

Errors

Check understanding

Lesson quiz

Score 4/5 or higher to mark this day complete.

1.Why put add/subtract/multiply/divide in separate functions?
2.What should you do if float(input(...)) fails?
3.Best response to division by zero in this project?
4.What does continue do inside the menu while-loop?
5.Which feature matches the Day 12 spec?