Project: Python Calculator
Build a command-line calculator with functions, error handling, and a menu loop.
Project Overview
Now that you've learned the fundamentals, let's build something real. This calculator runs in the terminal and performs basic arithmetic with proper error handling. It uses concepts from throughout the course — functions, loops, conditionals, and exception handling — all working together.
Core Functions
Define one function per operation. This keeps the code organised, each piece testable, and the
main program loop clean. Notice divide() checks for zero before attempting division.
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 "Error: divide by zero" return a / b print(add(10, 5)) print(divide(10, 0))
15 Error: divide by zero
Full Interactive Calculator
The main loop shows a menu, reads the choice, validates input, performs the operation, and loops
again. A dictionary maps choices to lambdas — this avoids a long if/elif chain and is more Pythonic.
The try/except catches non-numeric input without crashing.
def calculator(): print("=== Python Calculator ===") ops = {{ "1": ("+", lambda a,b: a+b), "2": ("-", lambda a,b: a-b), "3": ("×", lambda a,b: a*b), "4": ("÷", lambda a,b: a/b if b!=0 else "undefined") }} while True: print("\n1:Add 2:Sub 3:Mul 4:Div 5:Quit") c = input("Choose: ") if c == "5": print("Goodbye!"); break if c not in ops: print("Invalid"); continue try: a = float(input("First: ")) b = float(input("Second: ")) except ValueError: print("Enter valid numbers"); continue sym, fn = ops[c] print(f" {a} {sym} {b} = {fn(a,b)}") calculator()
=== Python Calculator === 1:Add 2:Sub 3:Mul 4:Div 5:Quit Choose: 3 First: 6 Second: 7 6.0 × 7.0 = 42.0
🧠 Quick Check
Which exception handles bad input when converting to float?