1. What a function is, and the three types
A function is a named block of statements that performs one task and runs only when called. Functions give reuse, modularity and readability, and make programs easier to test.
- Built-in: always available, e.g.
len(),print(),max(),round(),type(),int(). - From modules: need
importfirst, e.g.math.sqrt(),random.randint(),statistics.mean(). - User-defined: written with
def.
| Type | Where it comes from | Examples |
|---|---|---|
| Built-in | Always available | len(), print(), max(), round(), type() |
| From a module | Needs import first | math.sqrt(), random.randint(), statistics.mean() |
| User-defined | Written by you with def | def area(l, w): ... |
| Benefit | What it means |
|---|---|
| Reuse | Write the code once, call it many times |
| Modularity | Split a big program into small, named parts |
| Readability | A good name such as gst() explains the code |
| Easier testing | Check each function on its own |
| Less repetition | A change is made in one place only |
Key terms
- Function
A named, reusable block of code that runs when it is called.
- Module
A file of ready-made functions and constants, used after import, e.g. math.
2. math, random and statistics
import math then call math.name(); or from math import sqrt and call sqrt() directly.
- math:
sqrt(),pow(),fabs()return floats;ceil()rounds up andfloor()rounds down (towards minus infinity);math.pi. - random:
random()gives 0.0 ≤ x < 1.0;randint(a, b)includes both a and b;randrange(start, stop, step)excludes stop. - statistics:
mean(),median(),mode().
import math
from statistics import mean
print(math.floor(-2.5), math.ceil(-2.5), mean([3, 4, 8]))
Output: -3 -2 5
| Call | Result |
|---|---|
math.sqrt(81) | 9.0 |
math.ceil(6.1) | 7 |
math.floor(-6.1) | -7 |
math.pow(2, 3) | 8.0 |
math.fabs(-4) | 4.0 |
statistics.mean([4, 8, 9]) | 7 |
statistics.median([7, 1, 5, 3]) | 4.0 |
statistics.mode([2, 5, 2, 9]) | 2 |
| Call | Can return |
|---|---|
random.random() | a float from 0.0 up to (not including) 1.0 |
random.randint(1, 6) | an integer from 1 to 6 (both included) |
random.randrange(0, 20, 5) | one of [0, 5, 10, 15] (stop excluded) |
Key terms
- import
The statement that makes a module available, e.g. import math.
- randint(a, b)
Returns a random integer from a to b, including both ends.
3. Defining, calling and returning
Header: def name(parameters):, then an indented body. A function must be defined before it is called (else NameError). return sends a value back and ends the call; a function may have several returns, but only one runs. Without return, the call gives None.
def show_sq(n):
print(n * n)
def get_sq(n):
return n * n
a = show_sq(4)
b = get_sq(4)
print(a, b)
Output:
16
None 16
print() inside | return | |
|---|---|---|
| What it does | Shows the value on screen | Sends the value back to the caller |
| Value of the call | None | 16 |
| Can be used in an expression? | No | Yes, e.g. get_sq(4) + 1 |
| Step | Function returning | Arguments | Value returned |
|---|---|---|---|
| 1 | area() | 12, 10 | 120 |
| 2 | cost() | 12, 10 | 5400 |
| 3 | area() | 4, 3 | 12 |
| 4 | cost() | 4, 3 | 720 |
| 5 | main program (total) | — | 6120 |
Key terms
- Function header
The first line of a definition: def, name, parameters in brackets and a colon.
- return statement
Sends a value back to the caller and ends the function call.
- None
The value a function call gives when the function has no return statement.
4. Arguments and parameters
Parameters (formal) are the names in the header; arguments (actual) are the values in the call.
- Positional: matched by position.
- Default:
def f(a, b=5); used when the argument is left out; defaults must come after non-defaults. - Keyword:
f(b=2, a=1); matched by name, any order; must come after positional arguments.
def fee(days, rate=50, late=0):
return days * rate + late
print(fee(3), fee(3, 60), fee(3, late=25))
Output: 150 180 175
Call of ticket(age, fare=120) | Kind of passing | Returns |
|---|---|---|
ticket(10) | positional, default fare | 60 |
ticket(30) | positional, default fare | 120 |
ticket(8, 200) | positional, fare given | 100 |
ticket(fare=90, age=5) | keyword, any order | 45 |
| Term | Also called | Where | Example |
|---|---|---|---|
| Parameter | formal parameter | in the def header | days, rate in def fee(days, rate): |
| Argument | actual parameter | in the call | 4, 60 in fee(4, 60) |
| Rule | Wrong | Python says |
|---|---|---|
| Defaults come last in the header | def f(a=1, b): | SyntaxError |
| Positional before keyword in a call | f(a=1, 2) | SyntaxError |
| Every parameter needs a value | f(1) for def f(a, b) | TypeError |
| No value twice | f(1, a=2) | TypeError |
Key terms
- Default parameter
A parameter given a value in the header, used when the call leaves it out.
- Keyword argument
An argument passed as name=value, matched by name rather than position.
5. Returning several values; flow of execution
return a, b, c returns one tuple; receive it whole or unpack it: x, y, z = f().
Flow of execution: def statements are read first but their bodies run only when called; execution starts at the first statement outside functions; a call jumps into the body and control returns to the point of call when the function ends.
def split_time(m):
return m // 60, m % 60
t = split_time(200)
h, m = split_time(200)
print(t, h, m)
Output: (3, 20) 3 20
| Order | Line printed |
|---|---|
| 1 | 1: start |
| 2 | 2: in a |
| 3 | 3: in b |
| 4 | 4: back in a |
| 5 | 5: end |
Key terms
- Flow of execution
The order in which the statements of a program are run, including jumps into and out of functions.
- Unpacking
Assigning the items of a returned tuple to the same number of names.
6. Scope; mutable and immutable arguments
- Local: created inside a function (parameters too); exists only during the call.
- Global: created at the top level; can be read inside functions.
- To assign to a global inside a function, write
global namefirst; otherwise an assignment creates a local name (reading it first gives UnboundLocalError). - Immutable arguments (int, float, str, tuple) cannot be changed by the function; mutable ones (list, dict) can be changed in place and the caller sees the change. Rebinding a parameter (
L = []) never affects the caller.
def update(n, L):
n = n + 1
L.append(n)
num = 7
lst = [7]
update(num, lst)
print(num, lst)
Output: 7 [7, 8]
| Inside the function | Effect | Result |
|---|---|---|
only reads rate | uses the global value | works |
assigns count = 5 (no global) | creates a new local count | global unchanged |
count += 1 (no global) | reads a local name before it has a value | UnboundLocalError |
global count then count += 1 | changes the global variable | two calls give 2 |
| Call | a after line 2 | b after line 3 | Returns |
|---|---|---|---|
mystery(4) | 7 | 4 | 28 |
mystery(4, 1) | 5 | 4 | 20 |
Key terms
- Scope
The part of a program in which a name can be used.
- Local variable
A variable created inside a function; it exists only while that call runs.
- global keyword
Declares that a name inside a function refers to the global variable, so assignments change it.
Exam tips
Common mistakes
- Calling a function above its
def(NameError). - Printing inside a function and then using the call in an expression: it gives
None. - Writing defaults first:
def f(a=1, b)is a SyntaxError. - Putting a keyword argument before a positional one in a call.
- Forgetting
globalbefore assigning to a global (UnboundLocalError), or addingglobalwhen the function only reads the value. - Expecting an integer argument to change after the call, or a list argument to stay the same.
How marks are usually awarded
- Output questions: marks for each correct line, in the exact format (
None, tuples with brackets, floats with.0). - Error-finding: ½ or 1 mark per error found and corrected.
- Programs: marks for a correct header, correct logic,
returnused properly, the call, and the output. - Theory (2–3 marks): one point per mark, with a short code example where it helps.