>> Module 01 / Day 15 / Lecture

Build a Calculator

The Module 1 capstone
Three weeks of Python — variables, loops, conditions, functions — all aimed at this: a real little program, built the way professionals build them.
Lecture
75 min · 09:00–10:15
Lab
60 min · Simple Calculator
Module
M1 · Python Foundations
DAY 15 / 40
>> Today's roadmap

Recap, then build

  1. Recap the functions arc — everything is a function now
  2. Designing a program as a set of functions
  3. One function per operation — add, subtract, …
  4. A driver loop and a simple text menu
  5. Guarding against division by zero with if
  6. Lab — Simple Calculator (closes Module 1)
>> Where we've been · D11 – D14

Everything is a function now

Over the last four days you learned to name a piece of work and call it whenever you need it. That single idea changes how you write every program from here on.

D11 · DEFINE & CALL

def, parameters, return — package work behind a name.

D12 · PARAMS & RETURNS

Multiple params, defaults, and returning more than one value.

D13 · SCOPE

Local vs global — a function's variables stay inside the function.

D14 · REFACTOR

Turn one long messy script into small, named, reusable pieces.

>> 01 / 04 · How pros start

Design first: a program is a set of functions

Before writing any code, list the jobs the program must do. Each job becomes one function. A calculator has two kinds of jobs:

The maths jobs

Take two numbers, return an answer. Five of them: add, subtract, multiply, divide, modulo.
No input, no print — just math in, answer out.

The conductor job

One calculator() driver: ask the user what they want, call the right maths function, print the result.
All the input/print lives here.

>> 02 / 04 · One function per operation

Tiny functions, one job each

operations.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b
Take in, give back.
Each function takes two numbers and returns the answer. It does not print and does not ask for input. That's the driver's job.
>> 03 / 04 · The one that bites

Guard division by zero with if

crash.py
# No guard — Python stops dead:
def divide(a, b):
    return a / b

divide(7, 0)
# ZeroDivisionError: division by zero
guarded.py
# Check b BEFORE you divide:
def divide(a, b):
    if b == 0:
        return "Error: cannot divide by zero"
    return a / b

# Returns a number OR a message —
# the driver just prints whatever it gets.
>> 04 / 04 · The conductor

The driver — a simple text menu

Read what the user wants, then let if / elif / else choose which function to call.

driver.py
def calculator():
    a  = float(input("First number: "))
    op = input("Operator (+ - * / %): ")
    b  = float(input("Second number: "))

    if op == "+":
        result = add(a, b)
    elif op == "/":
        result = divide(a, b)
    # ... -, *, % in between ...
    else:
        print(f"Unknown operator: {op}")
        return

    print(f"{a} {op} {b} = {result}")
>> Putting it together

The whole shape of the program

Five tiny maths functions on top, one driver at the bottom. That's the entire design.

calculator.py
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: cannot divide by zero"
    return a / b
def modulo(a, b):
    if b == 0: return "Error: cannot divide by zero"
    return a % b

def calculator():
    # ask, choose with if/elif/else, print the result
    ...

if __name__ == "__main__":
    calculator()
>> Common failures

Five mistakes you'll make today

  1. Forgetting float() around the numbers — then "8" + "2" gives "82", not 10.
  2. Making a maths function print() instead of return — then the driver has nothing to show.
  3. Forgetting the divide-by-zero guard — one 0 and the whole program crashes.
  4. Converting the operator: + - * / % are just text — compare with ==, don't float() them.
  5. No else branch — an unknown symbol leaves result undefined and errors.
>> 11:00 – 12:00 · Lab

Today's lab — Simple Calculator

THE BUILD
Five functions + a driver

Write add, subtract, multiply, divide, modulo — then a calculator() that asks for two numbers and an operator and prints the result. Guard divide / modulo by zero.

★ STRETCH
History list

Loop so the user can keep calculating. Append each result to a history list (lists, from D3) and print it on request.

>> End of Day 15 · Module 1 complete

You've finished the foundations

  • ✓ Variables, types, input/output, and f-strings.
  • ✓ Conditions and loops to control the flow of a program.
  • ✓ Functions — and how to design a program as a set of them.
01 / 11
←/→ navigate   F fullscreen   Ctrl/⌘+P save as PDF