Simple Calculator
🧮 Simple Calculator
🎮 What We're Building
A menu-driven calculator: pick an operation, enter two numbers, get a result — and keep going until you choose to quit, without the program ever crashing on a mistake like dividing by zero.
Step 1: The Four Operations as Functions
Four small, single-purpose functions (Course 1, Chapter 8) — each takes two numbers and returns one result. Keeping each operation in its own function is what makes Step 3's menu logic clean: it just calls the right one, rather than repeating the arithmetic inline four separate times.
Step 2: Basic Error Handling — Division by Zero
The simplest form of error handling is a guard clause — a plain if check (Course 1, Chapter 3) before the risky operation, rather than letting it crash. Returning None signals "this didn't produce a real result," the same convention Course 2, Chapter 3's safe_divide() challenge used.
Step 3: A Menu Loop
The same while True + break shape from Chapter 1's guessing game — the menu keeps redisplaying until "5" is chosen. float(input(...)) allows decimal numbers, not just whole ones, wider than the int() conversion Chapter 1 used.
🏁 The Complete Calculator
Typing "five" for a number raises a ValueError from float(...), the exact same crash risk flagged in Chapter 1's guessing game. This version's "basic error handling" is specifically the division-by-zero guard — handling malformed number input too would mean reaching for try/except (Course 2, Chapter 3), left here as an extension rather than baked in, to keep this chapter's core build within Course 1-level tools.
Functions
Each operation is its own small, reusable function.
Guard clause
An if check before the risky operation — the simplest error handling.
Menu loop
while True + break, dispatching on the user's choice.
float() conversion
Allows decimal input, wider than int().
Try these on your own:
- Wrap the two
float(input(...))lines intry/except ValueError(Course 2, Chapter 3), printing a friendly message and returning to the menu instead of crashing. - Add an exponent operation (
**) and a modulo operation (%) as menu options 6 and 7. - Keep a running history of every calculation in a list, and add a menu option to print it all out.
- Instead of a numbered menu, accept an operator symbol directly (
+,-,*,/) as the choice.
🎯 What's Next
Next chapter: Password Generator — strings and the random/secrets modules.