Skip to content
Skip to page content
soylai.com

Functions — notes

6 sections 6 min readBeta

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 import first, e.g. math.sqrt(), random.randint(), statistics.mean().
  • User-defined: written with def.
Table of the three types of functions: built-in functions such as len and print, functions from modules such as math sqrt, random randint and statistics mean, and user-defined functions written with def
TypeWhere it comes fromExamples
Built-inAlways availablelen(), print(), max(), round(), type()
From a moduleNeeds import firstmath.sqrt(), random.randint(), statistics.mean()
User-definedWritten by you with defdef area(l, w): ...
Table of the benefits of functions: reuse, modularity, readability, easier testing and less repetition
BenefitWhat it means
ReuseWrite the code once, call it many times
ModularitySplit a big program into small, named parts
ReadabilityA good name such as gst() explains the code
Easier testingCheck each function on its own
Less repetitionA 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 and floor() 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

math.sqrt(), math.pow() and math.fabs() always return a float.
CallResult
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
Outputs change on every run, so exam questions ask for the possible values.
CallCan 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
The parts of a function definition and a call.
Program run: show_sq(4) prints 16 and returns None; get_sq(4) returns 16.
print() insidereturn
What it doesShows the value on screenSends the value back to the caller
Value of the callNone16
Can be used in an expression?NoYes, e.g. get_sq(4) + 1
Dry run produced by running the program in Python.
StepFunction returningArgumentsValue returned
1area()12, 10120
2cost()12, 105400
3area()4, 312
4cost()4, 3720
5main 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

Children under 12 pay half; the default fare is 120.
Call of ticket(age, fare=120)Kind of passingReturns
ticket(10)positional, default fare60
ticket(30)positional, default fare120
ticket(8, 200)positional, fare given100
ticket(fare=90, age=5)keyword, any order45
Table distinguishing parameters, the names in the def header such as days and rate, from arguments, the values in the call such as 4 and 60
TermAlso calledWhereExample
Parameterformal parameterin the def headerdays, rate in def fee(days, rate):
Argumentactual parameterin the call4, 60 in fee(4, 60)
Table of four argument rules with the error Python raises for each broken rule: defaults last in the header, positional arguments before keyword ones, a value for every parameter, and no parameter given twice
RuleWrongPython says
Defaults come last in the headerdef f(a=1, b):SyntaxError
Positional before keyword in a callf(a=1, 2)SyntaxError
Every parameter needs a valuef(1) for def f(a, b)TypeError
No value twicef(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

The number of names must match the number of values when unpacking.
def statements only create the functions; execution begins at the first line outside them.
OrderLine printed
11: start
22: in a
33: in b
44: back in a
55: 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 name first; 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]

A function can read global names; its local names vanish when the call ends.
Table of what happens to a global name inside a function: reading works; assigning without global creates a local; updating without global raises UnboundLocalError; with global the global value changes, so two calls give 2
Inside the functionEffectResult
only reads rateuses the global valueworks
assigns count = 5 (no global)creates a new local countglobal unchanged
count += 1 (no global)reads a local name before it has a valueUnboundLocalError
global count then count += 1changes the global variabletwo calls give 2
Immutable arguments are safe; mutable ones can be changed in place.
Dry run produced by running the function in Python; x in the caller stays 4.
Calla after line 2b after line 3Returns
mystery(4)7428
mystery(4, 1)5420

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 global before assigning to a global (UnboundLocalError), or adding global when 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, return used properly, the call, and the output.
  • Theory (2–3 marks): one point per mark, with a short code example where it helps.