Python Foundations

Functions

Modular programming — defining functions with def, calling them, passing parameters and arguments, returning values, and the Cambridge distinction between procedures and functions. Variable scope (local vs global) is covered on the next page.

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.
Key rule:
  • A function definition only describes what to do.
  • Nothing happens until the function is called.
  • Defining and calling are two separate events.
Exam tip:
  • 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.
Your Turn — Defining and calling a procedure [2 marks]
Write a procedure DisplayMessage that outputs "Programming is fun!". Then call the procedure.
Hint:
  • Identical shape to the worked example above
  • Just change the procedure name and the message
Your Turn [2 marks]
Write a procedure WelcomeUser that outputs "Welcome to the system.". Then call the procedure.

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!" appear

Cambridge pseudocode

PROCEDURE Greet()
    OUTPUT "Hello!"
ENDPROCEDURE

CALL Greet()
Key rule — call flow:
  • 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.
Exam tip — don't CALL a function:
  • Don't put CALL in front of a function.
  • In Cambridge pseudocode, CALL is for procedures only.
  • A function appears inside an expression — for example x ← Max(a, b) — never as a standalone CALL Max(a, b).
  • Writing CALL in front of a function is a classic 1-mark loss.
Your Turn — Two parameters [3 marks]
Write a Python function introduce that takes two parameters — a name (string) and an age (integer) — and prints "I am [name], and I am [age] years old.". Show a call to the function with arguments "Sara" and 17.
Your Turn [3 marks]
Write a Python function showProduct that takes two integer parameters and prints "The product is [result]", where [result] is the two numbers multiplied. Call it with arguments 6 and 4.

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.

TermMeaningWhere
ParameterA variable listed in the function header — an empty box labelled with a nameFunction header
ArgumentThe actual value passed to the function at the call — the value put into the boxThe 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: 8

Pseudocode (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.
Key rule — parameter order matters:
  • Arguments are matched to parameters strictly by position.
  • add_numbers(3, 5) makes a = 3 and b = 5, not the other way round.
  • If you swap the order at the call, you swap which value goes where.
Exam tip:
  • 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.
Your Turn — Return the smaller of two values [4 marks]
Write a Cambridge pseudocode function Min that takes two integer parameters and returns the smaller of the two. Then show how it would be called to output the smallest of 15 and 22.
Hint:
  • Same structure as Max
  • Just flip the comparison operator

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 expression

Pseudocode — RETURN + type

FUNCTION Square(num : INTEGER) RETURNS INTEGER
    RETURN num * num
ENDFUNCTION

DECLARE result : INTEGER
result <- Square(4)
OUTPUT result  // 16
Key rule — return ends the function immediately:
  • When RETURN runs, the function stops right there.
  • Any code after the RETURN on 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)
Exam tip:
  • If the question says "write a function", you must use RETURN.
  • If it says "write a procedure", you must not use RETURN — use OUTPUT or change a parameter passed by reference.
  • Reading the verb in the question carefully is worth at least 1 mark.

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.

FeatureProcedureFunction
Keyword pairPROCEDURE ... ENDPROCEDUREFUNCTION ... ENDFUNCTION
Returns a value?NoYes — one value
How invokedCALL Name(args) - a statementInside an expression, e.g. x <- Name(args)
Header includes return type?NoRETURNS <type>
Best forPerforming an action (output, file write, swap)Computing and returning a value (max, square, validate)
The one-question test:
  • 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 bannerProcedure. An action (output) with nothing to send back.
  • Take a number and return its squareFunction. Computes a single value the caller will use.
  • Swap two variablesProcedure (with BYREF parameters). A swap changes two values; a function can only return one.
  • Validate an email and return true/falseFunction. Returns a single Boolean the caller uses in a condition.
Exam tip:
  • 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.

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 balance
  • withdraw(amount) — subtract if enough funds; otherwise print an error
  • checkBalance() — 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.
Why this matters:
  • The global keyword is needed because deposit and withdraw modify the global balance.
  • checkBalance only reads it, so no global is needed there.
  • The full scope rules are on the next page — Local & Global Variables.

Key Points Summary

A function is a named block of code — it does not run until it is CALLED.
Three reasons to use functions: reuse, readability, debugging/testing.
Python: def name(params): body. Pseudocode: PROCEDURE/FUNCTION ... ENDPROCEDURE/ENDFUNCTION.
A call is a round trip: pause → run the body → return to the line after the call.
Parameter = the variable in the header. Argument = the value passed at the call.
Arguments match parameters by POSITION — order matters.
Cambridge pseudocode requires parameter types (name : INTEGER) and the default is pass-by-value.
return sends a value back AND ends the function immediately — code after it does not run.
A function call can be used directly in an expression: print(square(5) + 1) → 26.
CALL is for PROCEDURES only — never put CALL in front of a function.
Procedure = action, no return. Function = computes and returns one value (RETURNS type).
"Write a function" → must use RETURN. "Write a procedure" → must NOT use RETURN.

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.

Exam tip:
  • For every task, the marker checks: (1) correct def / FUNCTION header with the right parameter names, (2) the right loop or condition for the logic, (3) a return with the right value.
  • Missing the return is the single most common mark loss — always finish with one.
1Practice Task — Greetings function [2 marks]
Write a function Welcome(value) that returns "Welcome " followed by value.
2Practice Task — Smaller of two values [2 marks]
Write a function SmallerValue(num1, num2) that returns the smaller of two integers; returns either if equal.
3Practice Task — Greater-than check [3 marks]
Write a function GreaterThanCheck(num1, num2) that returns True if num1 > num2, otherwise False.
4Practice Task — PIN check [3 marks]
Write a function PinCheck(pin) that returns True only if pin == "4321".
5Practice Task — Non-negative check [3 marks]
Write a function NonNegativeCheck(n) that returns True if n >= 0.
6Practice Task — Odd check [3 marks]
Write a function OddCheck(n) that returns True if n is odd.
7Practice Task — Sum of squares to n [4 marks]
Write a function SumSquaresToN(n) that returns 1² + 2² + … + n².
8Practice Task — Power function [4 marks]
Write a function Power(base, exp) that returns base^exp using a loop.
9Practice Task — Count multiples [4 marks]
Write a function CountMultiples(numbers, k) that counts how many values in the list are divisible by k.
10Practice Task — Find minimum [4 marks]
Write a function FindMinimum(numbers) that returns the smallest value. Do not use the built-in min().
11Practice Task — Contains a value [4 marks]
Write a function ContainsValue(numbers, target) that returns True if target appears in the list.
12Practice Task — Count vowels [4 marks]
Write a function CountVowels(text) that counts a, e, i, o, u — both upper and lower case.
13Practice Task — Temperature label [5 marks]
Write a function TemperatureLabel(t) returning "Freezing", "Cold", "Warm", or "Hot" using sensible temperature ranges.
14Practice Task — Count non-empty lines in a file [5 marks]
Write a function CountNonEmptyLines(filename) that returns the number of lines that contain text (ignoring blank lines), and -1 on file error.
15Practice Task — Count valid ages [5 marks]
Write a function CountValidAges(ages) where valid ages are 0 to 120 inclusive.

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

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.