Lesson 4: Writing Functions — Packaging Reusable Logic
Write it once, name it well, call it anywhere • Sections 6.1 (Defining Functions), 6.2 (Control Flow), 6.5 (Return Values)
Save or Print Notes
Export this study guide as a clean PDF for exam preparation and quick revision.
1. Why Functions? Stop Copy-Pasting
When comparing three cars (e.g. 85,000 QR, 120,000 QR, 64,000 QR) with a monthly loan payment formula, typing the same logic three times hurts:
- The calculation is buried in input code.
- Reuse requires copy-pasting (violating DRY: Don't Repeat Yourself).
- One typo breaks the whole program.
- DEF (Define Once): A named block solving one specific job.
- RUN (Call by Name): Execute the body on demand with arguments.
- DRY (No Duplicate Code): Fix a bug once, and all callers benefit.
- DEC (Decompose): Split big problems into small, readable steps.
Anatomy of a def
def area(width, height):
result = width * height
return result
- Keyword:
def - Name:
area(uselower_snake_case) - Parameters:
(width, height) - Colon & Body: Indented 4 spaces; does not run until called!
2. Parameters vs Arguments & Positional Binding
| Concept | Where It Lives | What It Is | Who Writes It | Example |
|---|---|---|---|---|
| Parameter | In the def line |
A variable name waiting for a value | Function author | def pay(price, years): |
| Argument | At the call site | The actual value passed over | The caller | pay(85000, 5) |
loan_info(5, 85000), 5 binds to price and 85000 binds to years.
pay(85000) when 2 parameters are expected raises TypeError: pay() missing 1 required positional argument.
3. The Evolution: Version 1, 2, and 3
Version 1 vs Version 2
- Version 1 (No params, prints): Function asks user for everything and prints answer. Only works for car loans; cannot compare with budget.
- Version 2 (Params, prints): Caller supplies numbers:
loan_payment(85000, 6.5, 5). Works for any loan, but the answer is still trapped inside aprint()!
Version 3 (Parameters & return) — Best Practice!
A function computes and returns. The main program decides what to print, store, or compare.
def loan_payment(principle, annual_rate, years):
months = years * 12
monthly_rate = annual_rate / 100 / 12
growth = (1 + monthly_rate) ** months
payment = principle * monthly_rate * growth / (growth - 1)
return round(payment, 2)
# The caller captures and tests the result:
monthly = loan_payment(120000, 6.5, 5)
if monthly > 2000:
print(f"Payment of {monthly} QR is too much!")
4. What return Does (And What It Does Not)
return immediately terminates function execution and sends one value back to the caller expression.
returnhands a value back;print()only displays characters on screen.- Reaching a
returnstops the function at once! Lines after it never run. - A function that ends without running a
returnhands backNone. - A returned value can be stored, compared, printed, or passed into arithmetic.
def double(n):
print(n * 2) # Prints 42, but returns None!
result = double(21)
print(result + 1)
# TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
5. Returning Booleans & Function Decomposition
The Pythonic Boolean Return
Instead of five lines with if ... return True else: return False, return the condition directly:
# Clean 2-line version:
def score_valid(test_score):
return test_score >= 0 and test_score <= 100
print(score_valid(88)) # True
print(score_valid(120)) # False
Decomposition: Two Small Functions
Break complex formulas into small helpers. To compute combinations $C(n, k) = \frac{n!}{k!(n-k)!}$:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
def combination(n, k):
bottom = factorial(k) * factorial(n - k)
return factorial(n) / bottom
print(combination(8, 4)) # Output: 70.0