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
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":breaktry: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
- 01Applies functions, dicts, input handling and exceptions together.
- 02Dispatch by looking an operator up in a dict of functions — no long if/elif.
- 03Guard division by zero and invalid input with try/except.
- 04A loop turns it into a usable interactive tool.
- 05Stretch it with more operators, a running total, or unit tests.
