Learn
B2.3.4 | FUNCTIONS AND MODULARIZATION
01 | GIVE ONE JOB A NAME
A study planner needs to calculate a percentage for a quiz, a homework task and a practice exam. Copying the same calculation into three places makes a later correction easy to miss. A function lets us describe that job once, give it a name and use it wherever it is needed.
A function is a named unit of code that can be called to perform a task. It can receive inputs and return a result. Modularization organizes a larger solution into smaller units with clear responsibilities and interfaces.
This SL/HL lesson starts with functions inside one Python file, then builds a small two-file program. Java examples show the corresponding idea of methods.
02 | DEFINE FIRST, CALL WHEN NEEDED
def show_welcome():
print("Welcome to the study planner")
show_welcome()
show_welcome()
def creates a function definition. show_welcome is the name, parentheses hold the parameter list, and the colon introduces the body. The function body is the indented block executed when the function is called.
Reaching this definition does not print the welcome message. Each show_welcome() call executes the body, so the message appears twice.
The definition must have been executed before a call can use that name. A helper can appear later in the file than another function’s definition, provided it exists by the time the calling function actually uses it.
03 | A PARAMETER MAKES THE JOB REUSABLE
def greet(name):
print("Hello", name)
greet("Ada")
greet("Lin")
name is a parameter: a name in the function definition that receives a supplied value. "Ada" and "Lin" are arguments: values supplied by the calls.
For the first call, name refers to "Ada" inside that execution of greet. For the second call, it refers to "Lin". The body stays the same while the input changes.
Parameter names do not need to match the caller’s variable names. Calling greet(student_name) supplies the value referred to by student_name, not the literal text "student_name".
04 | TWO INPUTS, ONE RESULT
def rectangle_area(width, height):
area = width * height
return area
result = rectangle_area(4, 3)
print(result)
The positional arguments 4 and 3 are bound to width and height respectively. area becomes 12. return sends 12 back to the caller, where the assignment stores it in result. The final print displays 12.
A return value is useful because other code can store it, compare it or use it in another calculation. The function does not need to know how that result will eventually be displayed.
Read result = rectangle_area(4, 3) as “call the function, obtain its returned value, then assign that value to result”.
05 | FOLLOW CONTROL INTO THE CALL AND BACK
| Step | Where execution is | What happens |
|---|---|---|
| 1 | Caller | Evaluate rectangle_area(4, 3) |
| 2 | Function entry | Bind width = 4 and height = 3 |
| 3 | Function body | Calculate area = 12 |
| 4 | Return | Finish this call and provide 12 |
| 5 | Caller resumes | Assign result = 12 |
| 6 | Caller | Print result |
The caller pauses while this ordinary synchronous function runs. After return, execution resumes at the calling expression with the returned value. It does not restart the entire program.
Each active call has its own local execution state. A call stack tracks active calls and where control should resume; a helper called by another helper creates another active call until it returns.
06 | PRINT AND RETURN DO DIFFERENT JOBS
def display_double(number):
print(number * 2)
def calculate_double(number):
return number * 2
shown = display_double(6)
usable = calculate_double(6)
print("shown:", shown)
print("usable:", usable)
display_double prints 12 but reaches the end without an explicit return value, so Python returns None. shown therefore holds None. calculate_double returns 12 without printing it; usable holds 12.
The outputs are 12, then shown: None, then usable: 12. Seeing a number on screen does not mean that number was returned to the caller.
A Python function with no explicit return still returns None. In Java, a method declared void provides no return value. These are related ways to express a task focused on actions, but their language rules differ.
07 | INTERACTIVE: SEE THE ARGUMENT AND RESULT
Compare a returning function with one that only prints. Enter a whole number from 0 to 20 and step through a supplied call. The trace separates screen output from the value assigned by the caller.
08 | RETURN ENDS THE CURRENT CALL
def ticket_price(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age < 16:
return 5
return 8
print(ticket_price(12))
print(ticket_price(18))
For age 12, return 5 ends that call, so the later return 8 is not reached. For age 18, the child condition is false and return 8 provides the result. These prices are fictional teaching rules.
A return inside a loop also leaves the whole current function call, not merely that loop. Code after an unconditional return on the same execution path is unreachable.
If only some paths return a useful value, another path may fall through and return None. Design the result for every permitted input, including boundaries.
09 | POSITIONAL AND KEYWORD ARGUMENTS
def delivery_cost(distance, rate):
return distance * rate
print(delivery_cost(8, 2))
print(delivery_cost(rate=2, distance=8))
Positional arguments match parameters by order. Keyword arguments match by the parameter names, so their order can differ. Both calls return 16.
Names can make a call clearer when several inputs have the same type. delivery_cost(distance=8, rate=2) is easier to review than two unexplained numbers.
Supplying a required argument twice, omitting one or using an unknown keyword normally raises TypeError for this definition. A function’s interface tells callers which inputs are required.
10 | DEFAULT VALUES ARE OPTIONAL INPUTS
def add_fee(amount, fee=2):
return amount + fee
print(add_fee(10))
print(add_fee(10, fee=5))
fee has a default value of 2, used when the caller omits that argument. The calls return 12 and 15. Required positional parameters normally precede defaulted ones in this kind of definition.
Use defaults for sensible common choices, not to conceal missing essential information. A default is part of the function’s interface and should be documented.
Avoid a mutable list as a default accumulator: Python creates the default object once, so later calls can share changes. A common solution is a None default followed by creating a new list inside the call.
11 | LOCAL STATE BELONGS TO THE CALL
def add_bonus(score):
adjusted = score + 2
return adjusted
score = 10
result = add_bonus(score)
print(score)
print(result)
The parameter score and local adjusted belong to the function call. Rebinding that local state does not rebind the caller’s score. The outputs are 10 and 12. adjusted is not directly available by that name in the caller.
Pass required information as parameters and return results rather than relying on hidden global variables. Explicit inputs make a function easier to understand and test.
Local scope is not a promise that every object is copied. If a parameter refers to a mutable object, the body may be able to modify that shared object.
12 | MUTATION AND REBINDING ARE DIFFERENT
def add_score(scores, value):
scores.append(value)
results = [8, 5]
add_score(results, 7)
print(results)
The parameter scores and the caller’s results refer to the same list object. append changes that object, so the caller sees [8, 5, 7]. No list copy was made merely by passing the argument.
Assigning scores = [] inside the function would instead rebind the local parameter to another list, without replacing the caller’s results binding.
Document intentional mutation. If a function should leave the original unchanged, build and return a new list, for example return scores + [value]. Avoid describing all Python parameters simply as copies or as reference variables that can rebind the caller.
13 | DESIGN A SMALL FUNCTION CONTRACT
| Part of contract | Percentage example |
|---|---|
| Purpose | Calculate a percentage from a score and maximum |
| Inputs | Numeric score and maximum |
| Preconditions | maximum > 0; 0 <= score <= maximum |
| Result | score / maximum × 100 |
| Failure policy | Raise ValueError for invalid numeric bounds |
| Side effects | No printing or mutation |
A contract describes what callers may supply and what the function promises in response. Preconditions are requirements on inputs. Postconditions describe what should be true after normal completion.
A contract also explains responsibility: should the function validate inputs, or are callers required to validate them first? Be consistent rather than silently returning a misleading answer.
14 | CONSTRUCT A VALIDATED CALCULATION
def percentage(score, maximum):
"""Return a percentage for valid numeric score bounds."""
if maximum <= 0:
raise ValueError("Maximum must be positive")
if score < 0 or score > maximum:
raise ValueError("Score outside allowed range")
return score / maximum * 100
print(percentage(18, 24))
The result is 75.0. The guards reject invalid numeric bounds before division. The contract here assumes numeric inputs; converting arbitrary user text is handled separately.
The docstring is the string placed first in the function body. It describes the interface and behaviour. A clear name and short documentation help callers use the function correctly.
Testing 0 out of 24 should give 0.0 and 24 out of 24 should give 100.0. A maximum of 0 should raise the documented exception, rather than attempting division.
15 | ONE JOB PER FUNCTION
A function that asks for input, opens files, calculates results, formats a report and sends email has many reasons to change. Splitting those responsibilities lets us replace the interface without rewriting the calculation.
Cohesion describes how closely a unit’s contents support one focused purpose. A percentage calculation has a clear job. Unrelated printing, file deletion and email settings do not belong in that calculation merely because they occur somewhere in the same application.
Coupling concerns dependencies between units. Aim for clear, limited dependencies using explicit parameters and return values. Functions still need to cooperate; low coupling does not mean no communication.
16 | DECOMPOSE A REPORT INTO COOPERATING JOBS
For a small quiz report, separate calculating the percentage, selecting a message and formatting the final line. A coordinating function calls these jobs in order. The data moves through explicit return values.
Valid numeric inputs become a percentage.
The percentage becomes a message.
Values become a display string.
This is a dependency structure, not three programs running simultaneously. The coordinating code obtains each result before supplying it to the next job.
Modularization is more than splitting a long file every twenty lines. Choose boundaries that match responsibilities and keep related logic together.
17 | COMPLETE PROGRAM: A QUIZ REPORT
def percentage(score, maximum):
if maximum <= 0 or score < 0 or score > maximum:
raise ValueError("Invalid score bounds")
return score / maximum * 100
def feedback(percent):
if percent >= 70:
return "Secure understanding"
return "Keep practising"
def format_report(name, percent, message):
return f"{name}: {percent:.1f}% | {message}"
def make_report(name, score, maximum):
percent = percentage(score, maximum)
message = feedback(percent)
return format_report(name, percent, message)
print(make_report("Ada", 18, 24))
The output is Ada: 75.0% | Secure understanding. The 70% threshold is a fictional classroom rule, not an IB grade boundary. make_report coordinates the helpers and returns the completed string; the outer print controls display.
Trace the calls: make_report calls percentage and receives 75.0; feedback receives 75.0 and returns its message; format_report receives those values and returns the text. Finally make_report returns that text to its own caller.
Each helper can be tested separately. If the wording changes, feedback can change without altering the arithmetic.
18 | A MODULE IS A FILE YOU CAN IMPORT
In this Python example, a module is a .py file containing related definitions. Move the report functions into report_tools.py and put the application’s orchestration in main.py. Keep both files in the same project folder.
The import statement makes the module available to the importing code. report_tools.percentage refers to percentage in that module’s namespace. A namespace associates names with objects and helps distinguish identical names in different modules.
Do not name your own file math.py or random.py if you intend to import the standard module with that name: the local file can shadow the expected module.
19 | WORKED TWO-FILE PROJECT
Create report_tools.py with these related calculations and rules:
def percentage(score, maximum):
if maximum <= 0 or score < 0 or score > maximum:
raise ValueError("Invalid score bounds")
return score / maximum * 100
def feedback(percent):
if percent >= 70:
return "Secure understanding"
return "Keep practising"
Create main.py in the same folder, with this application entry point:
import report_tools
def main():
percent = report_tools.percentage(18, 24)
message = report_tools.feedback(percent)
print(f"Ada: {percent:.1f}% | {message}")
if __name__ == "__main__":
main()
In VS Code, open main.py and click Run. The output is Ada: 75.0% | Secure understanding. Keep report_tools.py saved beside it so the import resolves in this small project.
The application depends on report_tools; report_tools does not import main. Keeping this direction clear helps avoid circular imports and makes the calculation module reusable.
20 | IMPORTS AND THE MAIN GUARD
Python executes a module’s top-level statements when it is first imported in an ordinary interpreter session. Definitions are created, but top-level input or print calls also run if present. Later ordinary imports normally reuse the loaded module.
When a file runs directly, its __name__ is "__main__". When imported normally, its __name__ is its module name. The main guard calls main only when this file is the entry script.
The guard does not stop all top-level code from executing during import. It only controls the statements inside that if block. Put reusable definitions outside the guard and interactive startup inside main.
21 | JAVA: FUNCTIONS ARE EXPRESSED AS METHODS
public class ReportExample {
static double percentage(double score, double maximum) {
if (maximum <= 0 || score < 0 || score > maximum) {
throw new IllegalArgumentException("Invalid score bounds");
}
return score / maximum * 100;
}
static void showReport(String name, double percent) {
System.out.println(name + ": " + percent + "%");
}
public static void main(String[] args) {
double result = percentage(18, 24);
showReport("Ada", result);
}
}
A Java method belongs to a class. double declares the returned type for percentage; void declares no returned value for showReport. Parameter declarations include types.
These helpers are static so this small example can call them without constructing an instance. Instance methods operate through an object and are developed further with object-oriented programming.
Java passes argument values by value. For an object argument, the copied value is a reference to the object: a method can mutate that object, but reassigning its parameter does not reassign the caller’s variable.
22 | TEST THE UNIT BEFORE THE WHOLE PROGRAM
def percentage(score, maximum):
if maximum <= 0 or score < 0 or score > maximum:
raise ValueError("Invalid score bounds")
return score / maximum * 100
assert percentage(18, 24) == 75.0
assert percentage(0, 24) == 0.0
assert percentage(24, 24) == 100.0
try:
percentage(5, 0)
except ValueError:
print("Invalid maximum rejected")
else:
raise AssertionError("Expected ValueError")
A unit test checks a small unit in isolation. These tests cover a typical case, lower and upper valid score boundaries, and an invalid maximum. Tests should verify the promised behaviour, including errors.
Integration tests check cooperating units, such as make_report returning the correct complete text. Separate tests can distinguish a calculation defect from a formatting defect.
Floating-point results are not always exact. For less convenient fractions, use an appropriate tolerance, such as math.isclose, instead of assuming every decimal result can be compared exactly.
23 | RETURN MORE THAN ONE RELATED VALUE
def summarize(scores):
if len(scores) == 0:
raise ValueError("No scores")
total = 0
for score in scores:
total = total + score
return total, total / len(scores)
total, average = summarize([8, 5, 7])
print(total)
print(round(average, 2))
Python packages these two results into a tuple, which the caller unpacks into total and average. The outputs are 20 and 6.67. The order of unpacking must match the documented result order.
Return related values together when that expresses the task clearly. A long unexplained collection of unrelated results often suggests the function has too many responsibilities.
24 | REFACTOR WITHOUT CHANGING THE REQUIRED RESULT
Refactoring improves code structure while preserving its required observable behaviour. Extracting a repeated calculation into a function is a common example.
First identify the inputs the block reads and the outputs or side effects it produces. Turn required inputs into parameters and useful outputs into returned values. Replace each original block with a call, then run the existing tests.
Do not accidentally introduce a different rounding policy, change output order or stop updating a list that callers rely on. A shorter program is not automatically an equivalent program.
Modularity improves reuse, independent testing and maintenance, but excessive tiny wrappers or unclear interfaces can add navigation and coordination costs. Choose useful boundaries rather than maximizing the function count.
25 | COMMON ERRORS TO RECOGNIZE
| Symptom | Likely issue | Correction |
|---|---|---|
| Function name appears, nothing happens | Name referenced without calling | Use parentheses and required arguments |
| Caller receives None | Only printing or missing return path | Return the promised value on valid paths |
| Argument affects wrong calculation | Positional arguments reversed | Check interface; use keywords if helpful |
| Unexpected list changes | Shared mutable object modified | Document mutation or return a new object |
| Import starts user prompts | Interactive code at top level | Move startup to main and use a guard |
| Helpers depend on changing global state | Hidden dependencies | Use explicit parameters and returned results |
Read both sides of the interface: the definition promises a behaviour and the call supplies particular arguments. Many errors are a mismatch between those two views.
26 | CONSTRUCT A MODULAR SOLUTION
Start from the required output and identify meaningful jobs. For each function, write its purpose, inputs, result, error policy and side effects before writing the body. Then implement and test one unit at a time.
Use a coordinating function to connect results explicitly. Group related reusable functions into modules when that improves organization, and keep application startup separate from calculations.
Finally test the complete path as well as individual units. A well-designed module remains useful when its caller or user interface changes.