Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Functions in Python: def, parameters and return

After this lesson: I can write a function that takes values and returns a result.

60 min lesson3 commandsEveryday Linux commands lab: the thirty commands engineers type from memory

Writing a calculation once

A function in Python is a named block of code that you write once and use as often as you like. It takes values in, works on them and hands a result back.

A shop needs the area of a shelf in twenty places in its program. With a function, the sum is written once. Fix it there and every place is fixed.

By the end of this lesson

Note

I can write a function that takes values and returns a result.

Key words

WordWhat it meansExample
Functiona named block of code you can use again
Parametera name in the brackets that receives a valuewidth
Argumentthe actual value you give a function when you call it3
Return valuethe result a function hands back
Callto run a function by writing its name and bracketsarea(3, 4)
Scopethe part of a program where a name can be used

The cells students fill in are left blank in this preview.

def names a block of reusable code

Write def, a name, brackets and a colon. The indented lines below are the function. They run only when you call the function by writing its name.

The names in the brackets are parameters. They hold the values you pass in. The values you pass are arguments.

Worked example: calling area(3, 4)

StepWhat happensValues
1The call passes two arguments3 and 4
2The parameters receive themwidth is 3, height is 4
3The body works out width * height12
4return hands the result backthe call is replaced by 12

The cells students fill in are left blank in this preview.

Python has functions built in

Command
python3 -c "print(max(3, 9, 4), len('hello'), abs(-5))"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Your first function

Code: python
def area(width, height):
    return width * height

print(area(3, 4))
print(area(10, 2))
# Add a line that prints the area of a 5 by 5 square.

Save a function as a file

Command
printf 'def double(n):\n    return n * 2\n\nprint(double(21))\n' > double.py

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Run the file

Command
python3 double.py

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

return hands a value back

return ends the function and gives a value to the line that called it. The caller can store it, add to it or print it.

print only shows something on the screen. A function with no return hands back the special value None, which means "nothing".

Return and print side by side

Code: python
def show_total(a, b):
    print(a + b)

def get_total(a, b):
    return a + b

result = get_total(2, 3)
print("result is", result)
other = show_total(2, 3)
print("other is", other)

A common mistake

Warning

Many people end a function with print and expect to use the answer later. print shows the number but gives nothing back, so the caller receives None. Use return when another line needs the result.

Names made inside a function stay inside it

A variable created inside a function is local. It exists only while the function runs, and the rest of the program cannot see it.

If a line outside the function uses that name, Python stops with NameError: name 'tax' is not defined. Pass values in as arguments and get results out with return.

An assert is a small test

assert checks that a statement is True. If it is, nothing happens. If it is False, Python stops with an AssertionError.

Write a few asserts for the answers you expect. They show you at once when a change breaks a function. The hidden tests behind your assignments work this way.

Check a function with assert

Code: python
def is_even(n):
    return n % 2 == 0

assert is_even(4) == True
assert is_even(7) == False
assert is_even(0) == True
print("All checks passed")
# Add a check that fails, such as assert is_even(3) == True.

Going further

Write a function to_pence(pounds) that turns a price such as 2.5 into whole pence. Use round so that 2.5 gives 250 and 19.99 gives 1999.

Then write three asserts for it, including a price with two decimal places. Run them and read what Python says.

About this lab and its source: Everyday Linux commands lab: the thirty commands engineers type from memory

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.