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
| Word | What it means | Example |
|---|---|---|
| Function | a named block of code you can use again | |
| Parameter | a name in the brackets that receives a value | width |
| Argument | the actual value you give a function when you call it | 3 |
| Return value | the result a function hands back | |
| Call | to run a function by writing its name and brackets | area(3, 4) |
| Scope | the 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)
| Step | What happens | Values |
|---|---|---|
| 1 | The call passes two arguments | 3 and 4 |
| 2 | The parameters receive them | width is 3, height is 4 |
| 3 | The body works out width * height | 12 |
| 4 | return hands the result back | the call is replaced by 12 |
The cells students fill in are left blank in this preview.
Python has functions built in
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
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
printf 'def double(n):\n return n * 2\n\nprint(double(21))\n' > double.pyShown here, not run. Create a free account to press Run and type it into your own lab’s terminal.
Run the file
python3 double.pyShown 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
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
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.