5.1 What is a Function?
A function is a named block of code that performs a task. The code does not run when it is defined — it runs only when something calls the function by name. You can call the same function many times, each time with different inputs, and the same logic runs each time.
Three reasons to write functions, all of which Cambridge expects you to give:
- Reuse. Write the code once, use it many times. No copy-and-paste.
- Readability. A line like
total = Sum(marks)is easier to read than 30 lines of looping and adding. - Debugging and testing. A function is a small, self-contained unit — test it with a few inputs, prove it works, then trust it everywhere.
- A function definition only describes what to do.
- Nothing happens until the function is called.
- Defining and calling are two separate events.
- The exam question is almost always "the code does the same job repeatedly — modify it to use a function."
- If you see the same block of logic appearing more than once, extract it into a named function.
- Identical shape to the worked example above
- Just change the procedure name and the message
What is a Function?
5.2 Defining & Calling
Paper 4 questions usually start with "Write a function…" or "Write a procedure…". If your function header is wrong, you lose marks before the examiner even reads the body.
Python
# def + name + () + colon, body indented
def greet():
print("Hello!")
greet() # this is the CALL — only now does "Hello!" appearCambridge pseudocode
PROCEDURE Greet()
OUTPUT "Hello!"
ENDPROCEDURE
CALL Greet()- When a function or procedure is called, the program (1) pauses where it is, (2) jumps into the function body, (3) runs the body to the end or to a
RETURN, then (4) jumps back to exactly where it left off and continues. - A call is a round trip.
- Don't put
CALLin front of a function. - In Cambridge pseudocode,
CALLis for procedures only. - A function appears inside an expression — for example
x ← Max(a, b)— never as a standaloneCALL Max(a, b). - Writing
CALLin front of a function is a classic 1-mark loss.
Defining & Calling
5.3 Parameters & Arguments
A function with no inputs is rarely useful — it always does exactly the same thing. The point of a function is that you can give it different inputs and get different behaviour out. The words parameter and argument are not interchangeable.
| Term | Meaning | Where |
|---|---|---|
| Parameter | A variable listed in the function header — an empty box labelled with a name | Function header |
| Argument | The actual value passed to the function at the call — the value put into the box | The call site |
Python — one and two parameters
# One parameter
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # arg "Alice" -> param name
greet("Bob") # same function, different arg
# Two parameters
def add_numbers(a, b):
print(f"The sum is: {a + b}")
add_numbers(3, 5) # a=3, b=5 -> The sum is: 8Pseudocode (types required)
PROCEDURE Greet(name : STRING)
OUTPUT "Hello, ", name, "!"
ENDPROCEDURE
CALL Greet("Alice")
CALL Greet("Bob")
// Default is pass-by-value: the
// function receives a COPY of the
// argument.- Arguments are matched to parameters strictly by position.
add_numbers(3, 5)makesa = 3andb = 5, not the other way round.- If you swap the order at the call, you swap which value goes where.
- When asked to "define a function with two parameters", the marker checks three things — (1) correct keyword and name, (2) the right number of parameters in the right order, (3) those parameters actually used inside the body.
- A function that ignores its parameters scores zero for parameter use even if the header looks right.
- Same structure as Max
- Just flip the comparison operator
Parameters & Arguments
5.4 Return Values
Printing a result inside a function is a dead-end — once it is printed, you cannot use it again. Returning a result hands it back to the caller, who can store it in a variable, add it to other values, or pass it to another function. Cambridge mark schemes for "Write a function…" questions almost always require a RETURN — printing instead is a guaranteed mark loss.
Python — return
def square(num):
return num * num
result = square(4) # result is 16
print(result) # 16
print(square(5) + 1) # 26 — used in an expressionPseudocode — RETURN + type
FUNCTION Square(num : INTEGER) RETURNS INTEGER
RETURN num * num
ENDFUNCTION
DECLARE result : INTEGER
result <- Square(4)
OUTPUT result // 16- When
RETURNruns, the function stops right there. - Any code after the
RETURNon the same execution path is never executed. - This is true in both Python and Cambridge pseudocode.
Worked example — pseudocode Max function
Task: Write a Cambridge pseudocode function Max that takes two integer parameters and returns the larger of the two. [4 marks]
FUNCTION Max(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
IF Number1 > Number2 THEN
RETURN Number1
ELSE
RETURN Number2
ENDIF
ENDFUNCTION
OUTPUT "Penalty Fine = ", Max(10, Distance * 2)- If the question says "write a function", you must use
RETURN. - If it says "write a procedure", you must not use
RETURN— useOUTPUTor change a parameter passed by reference. - Reading the verb in the question carefully is worth at least 1 mark.
Return Values
5.5 Procedure vs Function
Python does not distinguish — every named block is just a function, and a function with no return simply returns None. Cambridge pseudocode does distinguish, and the question wording will tell you which one to write.
| Feature | Procedure | Function |
|---|---|---|
| Keyword pair | PROCEDURE ... ENDPROCEDURE | FUNCTION ... ENDFUNCTION |
| Returns a value? | No | Yes — one value |
| How invoked | CALL Name(args) - a statement | Inside an expression, e.g. x <- Name(args) |
| Header includes return type? | No | RETURNS <type> |
| Best for | Performing an action (output, file write, swap) | Computing and returning a value (max, square, validate) |
- Does the caller need a single value back?
- If yes → function.
- If no (the task is just an action) → procedure.
Worked example — choose procedure or function
Decide whether each task is better solved with a procedure or a function:
- Print a banner →
Procedure. An action (output) with nothing to send back. - Take a number and return its square →
Function. Computes a single value the caller will use. - Swap two variables →
Procedure(withBYREFparameters). A swap changes two values; a function can only return one. - Validate an email and return true/false →
Function. Returns a single Boolean the caller uses in a condition.
- When the question says "Write a function…" but your algorithm naturally has nothing to return, re-read the question — you have almost certainly misunderstood.
- Cambridge never asks you to write a function that has nothing useful to return.
- There will always be a sensible value to send back.
Procedure vs Function
5.6 Mini Project & Exam Focus
This is the standard Paper 4 "extend the existing program" question type — you are given a small system and must add functions. A bank account simulator with a balance and three operations:
deposit(amount)— add amount to balance and print the new balancewithdraw(amount)— subtract if enough funds; otherwise print an errorcheckBalance()— print the current balance
Python version (uses global — covered on the next page)
balance = 1000 # global
def deposit(amount):
global balance
balance = balance + amount
print(f"Deposited {amount}. New balance: {balance}")
def withdraw(amount):
global balance
if amount <= balance:
balance = balance - amount
print(f"Withdrew {amount}. New balance: {balance}")
else:
print("Insufficient funds.")
def checkBalance():
print(f"Current balance: {balance}")
# Test
deposit(500) # Deposited 500. New balance: 1500
withdraw(200) # Withdrew 200. New balance: 1300
checkBalance() # Current balance: 1300
withdraw(5000) # Insufficient funds.- The
globalkeyword is needed becausedepositandwithdrawmodify the globalbalance. checkBalanceonly reads it, so noglobalis needed there.- The full scope rules are on the next page — Local & Global Variables.
Key Points Recap
✓ Key Points Summary
5.7 Practice Tasks
Fifteen exam-style function-writing tasks. Each shows only the question — click Hint for the thought process, or Help for the worked solution. Try each one yourself before revealing.
- For every task, the marker checks: (1) correct
def/FUNCTIONheader with the right parameter names, (2) the right loop or condition for the logic, (3) areturnwith the right value. - Missing the
returnis the single most common mark loss — always finish with one.
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
Which keyword defines a function in Python?
Question 2True / False
A function definition runs its body the moment it is defined.
Question 3Multiple Choice
What is the difference between a parameter and an argument?
Question 4Multiple Choice
What is the output? def square(num): return num * num print(square(5) + 1)
Question 5True / False
In Cambridge pseudocode, CALL is used to invoke both procedures and functions.
Question 6Multiple Choice
Which is the correct Cambridge pseudocode function header for a function taking two integers and returning an integer?
Question 7Multiple Choice
What does the return statement do?
Question 8True / False
Arguments are matched to parameters strictly by position (order matters).
Question 9Multiple Choice
Which task is best solved with a PROCEDURE (not a function)?
Question 10True / False
In Python, a function with no return statement returns None.
Question 11Multiple Choice
If the question says "Write a function...", what must your answer include?
Question 12True / False
A function that ignores its parameters (does not use them in the body) still scores full marks if the header is correct.
Answer all 12 questions to enable submission.