Mini-Project: Robust Calculator
Before you start
#What you'll build
A calculator that accepts two numbers and an operator (+, -, *, /). It survives any bad input (non-numeric values, unknown operators, division by zero) and gives a clear, friendly message before asking again. The user has to type "quit" to leave.
Sample interaction
First number: ten
That doesn't look like a number. Try again.
First number: 10
Operator (+, -, *, /): plus
Unknown operator 'plus'. Use one of: + - * /
Operator (+, -, *, /): +
Second number: 0
10.0 + 0.0 = 10.0
First number: 10
Operator (+, -, *, /): /
Second number: 0
You can't divide by zero. Try again.
First number: quit
Bye!
#What you'll learn
After this lesson, you will be able to:
- Catch a specific exception with try/except rather than catching everything
- Loop until valid input arrives, instead of trusting the first thing typed
- Compose several validation layers without nesting six levels deep
#Step 1: Basic calculator (will crash)
The cheerful, fragile version. Works — as long as nobody types anything weird.
This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
a = float(input("First number: "))
op = input("Operator: ")
b = float(input("Second number: "))
if op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(a / b)ten for the first number. ValueError. Try / with b = 0. ZeroDivisionError. Try ?? for the operator. Silent nothing. We'll fix all three.What does this raise? result = 10 / 0
x / 0 — it raises a specific, named exception so you can catch it. Note that ZeroDivisionError is a subclass of ArithmeticError, so except ArithmeticError would catch it too, but catching the most specific type is always better. Floats are special: float('inf') / 0 also raises ZeroDivisionError, but 0.0 ** -1 raises it too while float('inf') + 1 happily returns inf. The takeaway: division by zero is always a Python error you must explicitly handle.What exception does `float('ten')` raise?
#Step 2: Catch ZeroDivisionError
b is 0 and the operator is /, Python raises ZeroDivisionError — catch it and print a message.try:
print(a / b)
except ZeroDivisionError:
print("You can't divide by zero.")try runs the risky code. If an exception of the matching type is raised, control jumps to the except block. Code after the try/except keeps running like nothing happened.What gets printed? try: x = int("hello") except ZeroDivisionError: print("zero") print("after")
#Step 3: Catch bad numbers
float("ten") raises ValueError. Wrap the input + conversion in try/except too.This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
try:
a = float(input("First number: "))
except ValueError:
print("That doesn't look like a number.")Now bad input prints a message instead of crashing. But the user is dropped out of the program. To keep them in, loop until they give valid input.
Why catch `ValueError` specifically instead of using a bare `except:` ?
#Step 4: Input validation loop
A helper that keeps asking for a number until it gets one. Returns the float when valid.
This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
def read_number(prompt):
while True:
raw = input(prompt)
if raw == "quit":
return None
try:
return float(raw)
except ValueError:
print("That doesn't look like a number. Try again.")while True + try/except + return is the universal "ask until valid" pattern. Returning None on "quit" lets the caller stop the main loop cleanly.What happens here? while True: try: x = int(input()) # user types "abc" break except ValueError: print("try again")
#Step 5: Validate the operator with a set
Operators are easier than numbers — just check membership in a small set.
This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
VALID_OPS = {"+", "-", "*", "/"}
def read_operator():
while True:
op = input("Operator (+, -, *, /): ").strip()
if op in VALID_OPS:
return op
print(f"Unknown operator {op!r}. Use one of: + - * /"){...} set syntax. op in VALID_OPS is O(1) lookup. {op!r} calls repr() so the message shows the operator with quotes — helpful when the user typed something weird with spaces.#Step 6: Glue everything into a robust main loop
def main():
while True:
a = read_number("First number: ")
if a is None:
break
op = read_operator()
b = read_number("Second number: ")
if b is None:
break
try:
if op == "+":
result = a + b
elif op == "-":
result = a - b
elif op == "*":
result = a * b
else:
result = a / b
print(f"{a} {op} {b} = {result}")
except ZeroDivisionError:
print("You can't divide by zero. Try again.")
print("Bye!")nan and inf, because float() parses them; checking math.isfinite is a good extension.#Now build it yourself
input() reads from the Input box: type every answer there, one per line, before you press Run.Calculator that never crashes
Build a calculator that accepts two numbers and an operator (+, -, *, /). The program must NEVER crash, no matter what the user types: not on letters, not on division by zero, not on unknown operators. Bad inputs print a friendly message and re-prompt. Typing 'quit' as a number ends the program. Name the helpers `read_number(prompt)` and `read_operator()`, print a good result like `10.0 + 0.0 = 10.0`, and finish with `Bye!`. Type the inputs, one per line, in the Input box above Run.
First number: ten
That doesn't look like a number. Try again.
First number: 10
Operator (+, -, *, /): plus
Unknown operator 'plus'. Use one of: + - * /
Operator (+, -, *, /): +
Second number: 0
10.0 + 0.0 = 10.0
First number: 10
Operator (+, -, *, /): /
Second number: 0
You can't divide by zero. Try again.
First number: quit
Bye!#Now make it your own
Try one of these variations:
- History. Keep a list of every successful computation and show "Last 5: ..." when the user types 'history' instead of a number.
- More operators. Add
**(power),%(modulo), and//(integer division). Update both VALID_OPS and the dispatch chain. - Replace if/elif with a dict — map operators to lambda functions:
OPS = {"+": lambda a, b: a + b, ...}. The dispatch becomes a single line:result = OPS[op](a, b).
#What's next
with open(...), handle a file that isn't there, and save your program's results so they survive after it closes.