Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Objectives: LO-5.1, LO-5.2, LO-5.3, LO-5.4
Prerequisites: Module 4
Time: about 5.5 hours: 2 for this reading, 2 for Lab 5, and 1.5 for the practice

You have called functions since Module 1: print, input, int, len, round, and math.isclose. Each one does a job you can use without knowing how it does it. In this module you write your own. A function is a named piece of code that takes values in, does one job, and hands a result back. Functions let you write a piece of work once and use it many times, give it a name that says what it does, and, most important, test it on its own.

Defining and calling a function

A def statement defines a function:

def rectangle_area(width, height):
    return width * height

Defining a function doesn’t run its body. Python only remembers it, under its name. The body runs when you call the function, by writing its name and the values to use in parentheses:

floor = rectangle_area(4, 2.5)
print(floor)
print(rectangle_area(3, 3) + 1)
10.0
10

The values in the call, 4 and 2.5, are the arguments. When the function is called, each parameter refers to its argument: width to 4 and height to 2.5. The call itself then stands for the value the function returned, so it can go anywhere a value can: in an assignment, a print, or a calculation.

Function names follow the same rules as variable names, and the same style: lowercase words joined by underscores. A good name is a verb or says what the function gives back: rectangle_area, is_even, read_score.

The flow of a call

When Python reaches a call, it leaves the line it was on, runs the function’s body with the parameters set to the arguments, and comes back to the same line when the function returns, carrying the value. Python Tutor shows this well: each call gets its own box, called a frame, which holds the function’s variables while it runs and disappears when it returns.

return and print are different

print shows a value on the screen. return hands a value back to the code that called the function, which can store it, test it, or use it in a calculation. A function that prints its answer gives nothing back:

def print_area(width, height):
    print(width * height)


result = print_area(2, 3)
print(result)
6
None

The 6 came from the print inside the function. result is None, Python’s value for “nothing”, because a function without a return returns None when it reaches the end of its body. So this fails:

print_area(2, 3) + 1
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

NoneType is the type of None. The rule of thumb: a function that works something out should return it. Leave the printing to the code that calls it, usually at the very end of the program. A returned value can be printed, tested, and used again; a printed one is gone.

return ends the function

return stops the function at once, even in the middle of a loop, which makes it a neat way to end a search:

def first_multiple(n, start):
    """Return the first multiple of n that is greater than or equal to start."""
    for number in range(start, start + n):
        if number % n == 0:
            return number

first_multiple(7, 40) returns 42 as soon as it finds it. A function may have several return statements, for example one in each branch of an if; whichever runs first ends the call. Make sure every path through the function reaches a return, or that path returns None.

Local and global names

A variable created inside a function, by assignment or as a parameter, is local to that function: it exists only while the function runs, and only inside it.

def make_greeting(name):
    greeting = "Hello, " + name
    return greeting


make_greeting("Ada")
print(greeting)
NameError: name 'greeting' is not defined

greeting and name lived in the call’s frame, and the frame disappeared when the function returned. To keep the result, store what the function returns: message = make_greeting("Ada").

A variable created outside any function, at the top level of a program or notebook, is global. A function can read a global variable, but an assignment inside a function always creates or changes a local one:

x = 10


def change():
    x = 20  # a new local x; the global x is untouched


change()
print(x)
10

Python decides that a name is local by looking at the whole function before it runs: if the function assigns to the name anywhere, the name is local everywhere in that function. That causes this error:

count = 0


def add_one():
    count = count + 1


add_one()
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

count = count + 1 assigns to count, so count is local in add_one, and the right side tries to read the local count before it has a value. Python has a global statement that lets a function assign to a global variable, but code that does is hard to follow and hard to test. Pass the value in, and return the new one:

def add_one(count):
    return count + 1


count = add_one(count)

Parameters are local too

A parameter is a local variable that starts as the argument. A parameter with the same name as a global variable is a different variable:

n = 1


def bump(n):
    n = n + 1
    return n


print(bump(5), n)
6 1

Inside bump, n is the parameter, which starts at 5. The global n stays 1.

Arguments: positional, keyword, and default

So far each argument went to the parameter in the same position. You can also name the parameter, with a keyword argument:

rectangle_area(height=2, width=5)

Keyword arguments can come in any order, and they make a call with several numbers readable: trip_cost(distance=420, price=1.85) says more than trip_cost(420, 1.85). You can mix the two kinds, but positional arguments come first: rectangle_area(5, height=2) works, and rectangle_area(width=5, 2) is SyntaxError: positional argument follows keyword argument.

A parameter can have a default value, used when the call leaves that argument out:

def price_with_tax(price, rate=0.08):
    return round(price * (1 + rate), 2)


print(price_with_tax(50))
print(price_with_tax(50, 0.2))
print(price_with_tax(50, rate=0))
54.0
60.0
50

Parameters with defaults come after the ones without. (The last line prints 50, not 50.0, because 50 * (1 + 0) is the integer 50, and round of an integer gives an integer.) You have used a default already: print’s end parameter is "\n" unless you give it another value.

Calls with the wrong number of arguments fail with a message that names the function:

CallMessage
rectangle_area(3)TypeError: rectangle_area() missing 1 required positional argument: 'height'
rectangle_area(3, 4, 5)TypeError: rectangle_area() takes 2 positional arguments but 3 were given

Docstrings

A docstring is a string written as the first line of a function’s body, in triple quotes. It says what the function does, what it takes, and what it returns:

def price_with_tax(price, rate=0.08):
    """Return price plus tax at rate, rounded to cents.

    rate is a fraction, so 0.08 means 8%.
    """
    return round(price * (1 + rate), 2)

The first line is a one-sentence summary in the imperative (“Return …”, not “Returns …”), as Python’s docstring conventions, PEP 257, recommend. Further lines, after a blank one, give details a caller needs. help(price_with_tax) prints the docstring, and VS Code shows it when you hover over a call. A comment explains how code works for someone reading it; a docstring tells someone calling the function what it does, without reading its body.

Breaking a problem into functions

A long script that does everything in one place is hard to read and hard to check. Split it into functions that each do one job, with a name that says what, then build the program out of them.

Worked example: a trip’s cost

This script works out the cost of a car trip, shared between passengers:

distance = 420  # km
efficiency = 6.5  # litres per 100 km
price = 1.85  # per litre
people = 3

litres = distance * efficiency / 100
cost = litres * price
each = cost / people
print(f"{litres:.1f} litres cost {cost:.2f}; each of {people} pays {each:.2f}")
27.3 litres cost 50.51; each of 3 pays 16.84

It has three jobs: work out the fuel, work out the cost, and share it. As functions:

def fuel_needed(distance_km, litres_per_100_km):
    """Return the litres of fuel a trip of distance_km needs."""
    return distance_km * litres_per_100_km / 100


def fuel_cost(litres, price_per_litre):
    """Return the cost of the given litres of fuel."""
    return litres * price_per_litre


def share(total, people):
    """Return each person's share when people split total equally."""
    return total / people


litres = fuel_needed(420, 6.5)
cost = fuel_cost(litres, 1.85)
print(f"{litres:.1f} litres cost {cost:.2f}; each of 3 pays {share(cost, 3):.2f}")

The output is the same. Each function is short enough to check by reading it, its name says what it does, and each can now be tested on its own.

Testing functions with assert

Module 3 tested decisions with assert, but had to change a variable and rerun the code for each test. A function makes each test one line: call it with an input whose answer you know, and assert the answer.

assert fuel_needed(100, 6.5) == 6.5
assert fuel_needed(0, 6.5) == 0
assert share(30, 3) == 10
assert math.isclose(fuel_cost(3, 1.1), 3.3)
print("all tests passed")

When a test fails, assert stops with an AssertionError. Add a message that shows what went wrong, so the failure explains itself:

result = share(30, 3)
assert result == 10, f"share(30, 3) gave {result}, expected 10"

Common misconceptions

BeliefWhat Python doesExample that breaks it
A function that prints its answer returns itIt returns Noneprint_area(2, 3) + 1 is a TypeError
Defining a function runs itOnly a call runs the bodyA def whose body prints prints nothing until it is called
A variable set inside a function exists afterwardIt is local, and disappears when the call endsprint(greeting) after make_greeting("Ada") is a NameError
Assigning to a global name inside a function changes the globalIt creates a local variableAfter change(), the global x is still 10
A parameter named like a global variable is that variableIt is a separate local variablebump(5) returns 6, and the global n stays 1
return only goes at the end of a functionIt can go anywhere, and ends the call at oncefirst_multiple returns from inside its loop
Keyword arguments must be in the parameters’ orderThey can be in any orderrectangle_area(height=2, width=5) is 10

Summary

Self-check

Answer each question before you open its answer.

  1. What does this print?

    def triple(x):
        print(x * 3)
    
    
    y = triple(4)
    print(y)

    Answer

    12, then None. The print inside triple shows 12, and triple returns None, because it has no return.

  2. After this code, what are a and the global b?

    b = 1
    
    
    def f(a):
        b = a * 2
        return b + 1
    
    
    a = f(5)

    Answer

    a is 11, and the global b is still 1. Inside f, b = a * 2 creates a local b (10), and the function returns 11.

  3. Given def greet(name, greeting="Hello"):, which of these calls work: greet("Ada"), greet(greeting="Hi", name="Ada"), greet(name="Ada", "Hi"), greet()?

    Answer

    The first two. greet(name="Ada", "Hi") is a SyntaxError, because a positional argument follows a keyword one. greet() is a TypeError, because name has no default.

  4. Write a function is_even(n) that returns True when n is even, and two assert tests for it.

    Answer

    def is_even(n):
        """Return True if n is even."""
        return n % 2 == 0
    
    
    assert is_even(4)
    assert not is_even(7)

    n % 2 == 0 is already True or False, so there’s no need for an if.

  5. Why is a function that returns its answer easier to test than one that prints it?

    Answer

    A test can compare a returned value with the expected one, in an assert. A printed value only appears on the screen, where code can’t check it without extra work.

Further reading