Skip to main content
Albero Academy

Project: Calculator

Build a command-line calculator applying functions, input handling and error handling.

Projects12 min

Time to consolidate the fundamentals. You'll build a command-line calculator that reads two numbers and an operator, computes the result, and handles bad input gracefully instead of crashing. It pulls together functions, dicts, loops and exceptions from the first modules.

What to build

  • Prompt the user for two numbers and an operator.
  • Dispatch via a dict of operator → function (cleaner than a long if/elif).
  • Handle division by zero and non-numeric input with try/except.
  • Loop until the user chooses to quit.

A starting scaffold

calculator.py
ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
}
def calc(a, op, b):
if op not in ops:
raise ValueError(f"unknown operator {op!r}")
return ops[op](a, b)
while True:
raw = input("e.g. 3 + 4 (or 'q'): ")
if raw.strip() == "q":
break
try:
a, op, b = raw.split()
print(calc(float(a), op, float(b)))
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError as e:
print(f"Invalid input: {e}")

Stretch goals

Add % and ** operators; support a running total ("ans"); or wrap the logic in tests with pytest (Module 11).

Key takeaways

  1. 01Applies functions, dicts, input handling and exceptions together.
  2. 02Dispatch by looking an operator up in a dict of functions — no long if/elif.
  3. 03Guard division by zero and invalid input with try/except.
  4. 04A loop turns it into a usable interactive tool.
  5. 05Stretch it with more operators, a running total, or unit tests.

Finished this chapter?

Mark it complete to track your progress through Python.