Functions
You have used many functions already: print(), len(), sorted(). Now you will write your own. A function is a named block of code. You write it once, then run it whenever you need it, just by using its name.
1def light_lamp():2 print("Fill the oil")3 print("Light the wick")4 5light_lamp()6light_lamp()
Fill the oil Light the wick Fill the oil Light the wick
Defining and calling
The first three lines define the function. They do not run it; they only teach Python a new name. The function runs when you call it: its name followed by parentheses.
| Piece | What it is |
|---|---|
def | short for "define": a new function starts here |
light_lamp | the function's name. Same rules as variable names. |
(): | parentheses, then a colon at the end of the line |
| the indented lines | the body: what runs each time the function is called |
What does this print?
1def say_hi():2 print("Hi!")3 4print("Start")
def only defines the function. Nothing calls say_hi(), so its body never runs.
Tip: Press Step on the first example. At each call, the current line jumps up into the function, runs its body, then comes back to the line after the call.
Parameters
A function gets more useful when you can hand it something to work with. Put a name between the parentheses: that is a parameter, a variable that gets its value from the call. The value you pass in the call is the argument.
1def light(street):2 print("Lighting the lamp on", street)3 4light("Mill Road")5light("Stone Bridge")
Lighting the lamp on Mill Road Lighting the lamp on Stone Bridge
Separate several parameters with commas. The arguments are matched up in order: the first one goes to the first parameter, and so on. Call with too few, and Python stops with a TypeError that names the missing one.
1def deliver(ore, count):2 print(f"Delivering {count} {ore}")3 4deliver("iron", 12)5deliver("gold")
Delivering 12 iron
Traceback (most recent call last):
File "main.py", line 5, in <module>
deliver("gold")
TypeError: deliver() missing 1 required positional argument: 'count'Giving back a value with return
print shows a value on the screen. return does something different: it ends the function and hands a value back to the place where it was called. You can store that value, print it, or use it in a sum, just like the result of len().
1def area(width, height):2 return width * height3 4room = area(4, 3)5print(room)6print(area(2, 5) + area(1, 1))
12 11
Press Step here: when the call starts, width and height appear as the function's own variables. When return runs, they disappear, and the call is replaced by the value it gave back.
print or return?
A function that only prints shows something, but gives nothing back. A function without a return returns None.
What does the second line of output say?
1def double(n):2 print(n * 2)3 4result = double(5)5print(result)
double(5) prints 10 itself, but has no return, so it gives back None. That None is stored in result and printed.
print(x) | return x | |
|---|---|---|
Shows x on the screen | yes | no |
Gives x back to the caller | no | yes |
| Ends the function | no | yes |
Most functions should return their result and let the caller decide what to do with it. That way the same function works in a sum, an if, or a print.
Returning early
return ends the function straight away, even in the middle. Lines after it in the function do not run. This makes a good way to deal with special cases first:
1def ore_price(ore):2 if ore == "gold":3 return 204 if ore == "copper":5 return 66 return 47 8print(ore_price("gold"))9print(ore_price("copper"))10print(ore_price("coal"))
20 6 4
A return inside a loop stops both the loop and the function. Here the function returns the first empty lamp it finds:
1def first_empty(oil):2 for i, level in enumerate(oil):3 if level == 0:4 return i5 return -16 7print(first_empty([5, 3, 0, 7, 0]))8print(first_empty([5, 3]))
2 -1
Returning several values
Write several values after return, separated by commas, and the function returns them as a tuple. Unpack it to give each value its own name, just as you did with divmod() in lesson 10.
1def lowest_highest(numbers):2 return min(numbers), max(numbers)3 4print(lowest_highest([4, 9, 2, 7]))5low, high = lowest_highest([4, 9, 2, 7])6print("from", low, "to", high)
(2, 9) from 2 to 9
Docstrings and helpers
A string written as the first line of the body is a docstring: a note that says what the function does. It does not print anything. Tools and editors show it to people who use your function. Triple quotes """ let it run over several lines.
Functions can call other functions. Small functions that each do one job can be combined into bigger ones:
1def area(width, height):2 """Return the area of a rectangle."""3 return width * height4 5def floor_price(width, height):6 """Return the price of tiling a floor.78 One square meter of tiles costs 12 coins.9 """10 return area(width, height) * 1211 12print(floor_price(4, 3))13print(floor_price(2, 2))
144 48
Press Step and watch the calls nest: floor_price calls area, area returns its value to floor_price, and floor_price returns to the print line.
Why bother with functions?
- Write it once. Fix a bug in one place, not in every copy.
- Give it a name.
floor_price(4, 3)says what it does; the arithmetic alone does not. - Think in pieces. Each function can be tested and understood on its own.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it. Each function should return its result; the print lines are already there.
Lamp label
✓Write a function label(n) that returns the text Lamp n for the number n.
Lamp 1 Lamp 12
1# Write label(n) here2 3print(label(1))4print(label(12))
Full or not
✓Finish cart_status(load): return "full" when the load is 10 or more, "empty" when it is 0, and "loading" otherwise.
full empty loading
1def cart_status(load):2 return "loading"3 4print(cart_status(12))5print(cart_status(0))6print(cart_status(4))
Total and average
✓Write summary(loads) that returns two values: the total of the list and its average.
18 6.0
1# Write summary(loads) here2 3total, average = summary([4, 8, 6])4print(total, average)
What you learned
def name(parameters):defines a function; the body runs only when you callname(arguments).- Arguments are matched to parameters in order; a missing one is a
TypeError. returnends the function and gives a value back. Without it, a function returnsNone.printshows a value;returnhands it back so the caller can use it.return a, breturns a tuple you can unpack. A docstring says what a function does.