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 * heightdefis followed by the function’s name, its parameters in parentheses, and a colon. Parameters are names for the values the function will be given.The indented block is the function’s body.
returnends the function and hands a value back to the code that called it.
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
10The 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
NoneThe 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) + 1TypeError: 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 numberfirst_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 definedgreeting 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)10Python 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 valuecount = 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 1Inside 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
50Parameters 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:
| Call | Message |
|---|---|
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.84It 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")Choose inputs whose answers you can work out by hand: round numbers, zero, and the boundaries of any decision inside the function, as in Module 3.
Compare a float that the function calculates with
math.isclose, not==(afterimport math).3 * 1.1is3.3000000000000003as a float, sofuel_cost(3, 1.1) == 3.3isFalse.Write the tests as soon as you write the function, or before: writing the tests first makes you decide exactly what the function should do. Module 13 builds on this with a testing tool, pytest.
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¶
| Belief | What Python does | Example that breaks it |
|---|---|---|
| A function that prints its answer returns it | It returns None | print_area(2, 3) + 1 is a TypeError |
| Defining a function runs it | Only a call runs the body | A def whose body prints prints nothing until it is called |
| A variable set inside a function exists afterward | It is local, and disappears when the call ends | print(greeting) after make_greeting("Ada") is a NameError |
| Assigning to a global name inside a function changes the global | It creates a local variable | After change(), the global x is still 10 |
| A parameter named like a global variable is that variable | It is a separate local variable | bump(5) returns 6, and the global n stays 1 |
return only goes at the end of a function | It can go anywhere, and ends the call at once | first_multiple returns from inside its loop |
| Keyword arguments must be in the parameters’ order | They can be in any order | rectangle_area(height=2, width=5) is 10 |
Summary¶
def name(parameters):defines a function, and its body runs only when it is called. Each call sets the parameters to the arguments.returnhands a value back and ends the call. A function with noreturnreturnsNone. Functions that work something out should return it, not print it.Variables assigned inside a function, and its parameters, are local. A function can read a global variable, but assigning to a name makes it local throughout the function.
Arguments can be positional or keyword, and parameters can have default values. Positional arguments come before keyword ones, and parameters without defaults before those with them.
A docstring says what a function does, takes, and returns.
Split a long program into small functions that each do one job, and test each with
assert.
Self-check¶
Answer each question before you open its answer.
What does this print?
def triple(x): print(x * 3) y = triple(4) print(y)Answer
12, thenNone. Theprintinsidetripleshows 12, andtriplereturnsNone, because it has noreturn.After this code, what are
aand the globalb?b = 1 def f(a): b = a * 2 return b + 1 a = f(5)Answer
ais11, and the globalbis still1. Insidef,b = a * 2creates a localb(10), and the function returns 11.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 aSyntaxError, because a positional argument follows a keyword one.greet()is aTypeError, becausenamehas no default.Write a function
is_even(n)that returnsTruewhennis even, and twoasserttests 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 == 0is alreadyTrueorFalse, so there’s no need for anif.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¶
The Python Tutorial, sections 4.8, Defining Functions, and 4.9, More on Defining Functions. Default and keyword arguments, and docstrings, in the language’s own words. Section 4.9 goes further than this module, into features such as
*args, which later modules use.PEP 257, Docstring Conventions. The conventions for writing docstrings: what the summary line says, and how longer docstrings are laid out.
Allen B. Downey, Think Python, 3rd edition, chapter 3, Functions, and chapter 6, Return Values. Defining functions, local variables drawn as stack diagrams, and functions that return values, with incremental development: building a function a few lines at a time and testing as you go.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 4, Functions. Parameters, return values,
None, keyword arguments (which it calls named parameters), and local and global scope, with examples of each.