Simple Calculator

Python Projects (Beginner)
Course 4 ยท Chapter 2 ยท Simple Calculator

๐Ÿงฎ Simple Calculator

A command-line calculator: four operations, a repeating menu, and just enough error handling that a bad input doesn't crash the whole program. Built entirely from functions and conditionals โ€” Course 1 material, put to real use.

๐ŸŽฎ 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

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):
    return a / b

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

def divide(a, b):
    if b == 0:
        print("Error: can't divide by zero")
        return None
    return a / b

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

while True:
    print("\n1. Add  2. Subtract  3. Multiply  4. Divide  5. Quit")
    choice = input("Choose an option: ")

    if choice == "5":
        print("Goodbye!")
        break

    a = float(input("First number: "))
    b = float(input("Second number: "))

    if choice == "1":
        print("Result:", add(a, b))
    elif choice == "2":
        print("Result:", subtract(a, b))
    elif choice == "3":
        print("Result:", multiply(a, b))
    elif choice == "4":
        print("Result:", divide(a, b))
    else:
        print("Not a valid option, try again.")

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

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:
        print("Error: can't divide by zero")
        return None
    return a / b

while True:
    print("\n1. Add  2. Subtract  3. Multiply  4. Divide  5. Quit")
    choice = input("Choose an option: ")

    if choice == "5":
        print("Goodbye!")
        break

    a = float(input("First number: "))
    b = float(input("Second number: "))

    if choice == "1":
        print("Result:", add(a, b))
    elif choice == "2":
        print("Result:", subtract(a, b))
    elif choice == "3":
        print("Result:", multiply(a, b))
    elif choice == "4":
        print("Result:", divide(a, b))
    else:
        print("Not a valid option, try again.")
โš  Non-Numeric Input Still Crashes This Version

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().

๐Ÿš€ Extend This Project

Try these on your own:

  • Wrap the two float(input(...)) lines in try/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.