B2.3.4 Functions and modular programs
SL + HLCommand term: Construct1. Inside a function call: the call stack
One function calls two others. Watch each call push a new frame holding its parameters and local variables, and each return pop it off and hand back a value.
2. Function machine: same code, different inputs
A function is a reusable machine: arguments go in, a value comes out. Try different arguments. Then compare a function that returns with one that only prints.
3. Maintenance challenge: copy-paste vs a function
The library changes its fine from 0.5 to 0.75 per day. Click every place that must change in each version (yellow), then run both. Which version is easier and safer to maintain?
Copy-and-paste version
Modular version
4. Design the modules
Split ShelfWise into three modules, each with one clear responsibility. Assign each function, check, and see the import statements main.py would need.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Predict the output
Trace each call. Streaks of 3+ score double.
7. Which benefit of modularization?
Each scenario shows one main benefit of splitting code into functions and modules.
8. 45-second speed round: what is returned?
A new function and call each time.
catalogue.py (books), loans.py (borrowing rules) and main.py (the program). Every function takes what it needs as parameters and gives back a return value: no global variables.Expected output (run main.py)
Think about it
(1) Why does lend take catalogue and loans as parameters instead of using global variables? (2) What does if __name__ == "__main__": allow another module to do? (3) Which module would change if the library introduced a new fine rule, and which would not?
Check my modules
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: A conversion table with functions
Write c_to_f(c) and f_to_c(f), then table(start, stop, step) that uses c_to_f to print a neatly aligned Celsius-to-Fahrenheit table.
Starter file (write your code where it says pass # your code here):
def c_to_f(c):
pass # your code here
def f_to_c(f):
pass # your code here
def table(start, stop, step):
pass # your code here
# ---- tests ----
table(-10, 40, 10)
print(round(f_to_c(98.6), 1))
Expected output when your code is correct:
C F
-10 14.0
0 32.0
10 50.0
20 68.0
30 86.0
40 104.0
37.0
Hint
{x:>6.1f}, to line up columns.Model solution
def c_to_f(c):
return c * 9 / 5 + 32
def f_to_c(f):
return (f - 32) * 5 / 9
def table(start, stop, step):
print(f"{'C':>5} {'F':>6}")
for c in range(start, stop + 1, step):
print(f"{c:>5} {c_to_f(c):>6.1f}")
# ---- tests ----
table(-10, 40, 10)
print(round(f_to_c(98.6), 1))
Task 2: A modular report card
Break this problem into small functions: mean(marks), letter(avg) (A for 80+, B for 65+, C for 50+, otherwise D) and report(name, marks) that returns one line like "Ana: mean 81.3 grade A". report must call the other two.
Starter file (write your code where it says pass # your code here):
def mean(marks):
pass # your code here
def letter(avg):
pass # your code here
def report(name, marks):
pass # your code here
# ---- tests ----
for name, marks in [("Ana", [78, 85, 81]), ("Ben", [60, 70, 66]), ("Cai", [40, 52, 49])]:
print(report(name, marks))
Expected output when your code is correct:
Ana: mean 81.3 grade A Ben: mean 65.3 grade B Cai: mean 47.0 grade D
Hint
Model solution
def mean(marks):
return sum(marks) / len(marks)
def letter(avg):
if avg >= 80:
return "A"
elif avg >= 65:
return "B"
elif avg >= 50:
return "C"
return "D"
def report(name, marks):
avg = mean(marks)
return f"{name}: mean {avg:.1f} grade {letter(avg)}"
# ---- tests ----
for name, marks in [("Ana", [78, 85, 81]), ("Ben", [60, 70, 66]), ("Cai", [40, 52, 49])]:
print(report(name, marks))
Task 3: Validate a student record
A record is a dictionary such as {"id": "S0042", "name": "Ana Li", "year": 12, "email": "ana@school.cn"}. Write separate helper functions valid_id (S followed by 4 digits), valid_name (at least two words, letters and spaces only), valid_year (11 or 12), valid_email (exactly one @ and a dot after it), and validate(record) that returns a list of the names of fields that fail. Missing fields also fail.
Starter file (write your code where it says pass # your code here):
def valid_id(v):
pass # your code here
def valid_name(v):
pass # your code here
def valid_year(v):
pass # your code here
def valid_email(v):
pass # your code here
def validate(record):
pass # your code here
# ---- tests ----
print(validate({"id": "S0042", "name": "Ana Li", "year": 12, "email": "ana@school.cn"}))
print(validate({"id": "s42", "name": "Ana", "year": 13, "email": "ana@school"}))
print(validate({"name": "Ben Wu 2", "year": 11}))
Expected output when your code is correct:
[] ['id', 'name', 'year', 'email'] ['id', 'name', 'email']
Hint
Model solution
def valid_id(v):
return isinstance(v, str) and len(v) == 5 and v[0] == "S" and v[1:].isdigit()
def valid_name(v):
return isinstance(v, str) and len(v.split()) >= 2 and all(w.isalpha() for w in v.split())
def valid_year(v):
return v in (11, 12)
def valid_email(v):
if not isinstance(v, str) or v.count("@") != 1:
return False
return "." in v.split("@")[1]
def validate(record):
checks = {"id": valid_id, "name": valid_name, "year": valid_year, "email": valid_email}
return [field for field, check in checks.items() if field not in record or not check(record[field])]
# ---- tests ----
print(validate({"id": "S0042", "name": "Ana Li", "year": 12, "email": "ana@school.cn"}))
print(validate({"id": "s42", "name": "Ana", "year": 13, "email": "ana@school"}))
print(validate({"name": "Ben Wu 2", "year": 11}))
Learning objectives
By the end of this page you should be able to:
- Construct functions with parameters and return values, and call them with different arguments to reuse the same code.
- Distinguish between parameters and arguments, and between returning a value and printing it, and trace function calls using the call stack.
- Explain the principles of scope (local versus global) and why functions should communicate through parameters and return values.
- Construct a modular program split into functions and modules, each with a single clear responsibility, using import.
- Explain the benefits of modularization (reuse, maintainability, testing, readability and teamwork) in given scenarios.
Functions
def calculate_fine(days_held, is_teacher=False): # definition: parameters
"""Return the fine for a book kept days_held days."""
late = days_held - 14 # local variable
fine = late * 0.5 if late > 0 else 0.0
if is_teacher:
fine = fine / 2
return fine # output
f = calculate_fine(20) # call with an argument: f = 3.0
t = calculate_fine(20, True) # same code, different inputs: 1.5
- A function is a named, reusable block of code that performs one task. It runs only when it is called.
- Parameters are the variables in the definition (
days_held); arguments are the actual values passed in a call (20). A default parameter (is_teacher=False) may be left out. - return sends a value back to the caller and ends the function. A function with no return gives back
None. Printing is not returning: a printed value cannot be stored or used in a calculation. - In Java a function is a method with declared types:
static double calculateFine(int daysHeld, boolean isTeacher) { ... };voidmeans no return value. - Each call gets its own frame on the call stack (B2.2.3), holding its parameters and locals; the frame is removed when the function returns.
Scope principles
- Local variables (including parameters) exist only inside their function, during the call. Two functions can both use a variable called
totalwithout interfering. - Global variables are visible everywhere, but a function that changes them (with
global) is harder to understand, test and reuse, because its behaviour depends on hidden state. - Good practice: pass data in as parameters and send results out with return. Keep globals for constants such as
LOAN_DAYS = 14.
Modularization
Modularization divides a program into separate, self-contained parts: functions, and modules (separate files) that group related functions. It is decomposition (B1.1.2) applied to code.
# main.py
from catalogue import find_book, available
from loans import calculate_fine, lend
def main():
...
if __name__ == "__main__": # run main() only when this file is run directly,
main() # not when another module imports it
Java organises code into classes and packages in the same spirit (B3).
Benefits
| Benefit | Why | ShelfWise example |
|---|---|---|
| Reuse | Write once, call many times, even from other programs | calculate_fine is used by the desk, the reports and the reminder emails |
| Maintainability | A change is made in one place | A new fine rate means editing one function, not ten copies |
| Testing and debugging | Each function can be tested on its own; bugs are isolated | Test calculate_fine with boundary data before connecting the menu |
| Readability | Named functions describe what happens; the main program reads like a plan | if available(books, title): lend(...) |
| Teamwork | Different people can build different modules at the same time | One student writes loans.py while another writes the user interface |
Designing good functions
- One job per function, with a descriptive verb name (
calculate_fine, notf2). - Short enough to read on one screen; a docstring describing inputs and output.
- Avoid side effects such as printing or changing globals, unless that is the function's job.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Distinguish between a parameter and an argument. [2]
2. Explain two benefits of modularization for the team developing ShelfWise. [4]
3. State the output. [3]
def double(n):
n = n * 2
return n
x = 5
y = double(x)
print(x, y, double(double(1)))
5 10 4.4. Construct a Python function average(values) that returns the mean of a list of numbers, or 0 if the list is empty. [4]
if len(values) == 0: return 0 [1]; total the values with a loop (or sum) [1]; return total / len(values) [1].5. Explain why functions should use parameters and return values rather than global variables. [3]
6. Outline the difference between a function that returns a value and one that prints it. [2]