Phase 1 · Programming Fundamentals
Project: Calculator
Build a CLI calculator with functions, a looped menu, and solid input validation.
On this page
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
=== Calculator ===
1) add
2) subtract
3) multiply
4) divide
5) quit
Choose: 1
a: 12
b: 5
Result: 17.0Step 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).
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.
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 testPractice
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".
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.