add, subtract, …ifOver 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.
def, parameters, return — package work behind a name.
Multiple params, defaults, and returning more than one value.
Local vs global — a function's variables stay inside the function.
Turn one long messy script into small, named, reusable pieces.
Before writing any code, list the jobs the program must do. Each job becomes one function. A calculator has two kinds of jobs:
Take two numbers, return an answer. Five of them: add, subtract, multiply, divide, modulo.
No input, no print — just math in, answer out.
One calculator() driver: ask the user what they want, call the right maths function, print the result.
All the input/print lives here.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
returns the answer. It does not print and does not ask for input. That's the driver's job.
if# No guard — Python stops dead:
def divide(a, b):
return a / b
divide(7, 0)
# ZeroDivisionError: division by zero
# 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.
%. Modulo by zero crashes too — 7 % 0 raises the same error. Guard modulo() the exact same way.
Read what the user wants, then let if / elif / else choose which function to call.
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}")
Five tiny maths functions on top, one driver at the bottom. That's the entire design.
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()
float() around the numbers — then "8" + "2" gives "82", not 10.print() instead of return — then the driver has nothing to show.0 and the whole program crashes.+ - * / % are just text — compare with ==, don't float() them.else branch — an unknown symbol leaves result undefined and errors.
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.
Loop so the user can keep calculating. Append each result to a history list (lists, from D3) and print it on request.
students/<your-username>/D15_calculator.py. Full brief in lab/module_1_foundations/D15_calculator/problem.md. PR before 12:00.
String methods: split, join, replace, strip.