Kodewick
Lesson 16 of 31Contents

Functions

Lesson 16 of 31 · Part 3 · Functions · about 20 minutes

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.

main.py
1def light_lamp():2    print("Fill the oil")3    print("Light the wick")4 5light_lamp()6light_lamp()
Output
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.

PieceWhat it is
defshort for "define": a new function starts here
light_lampthe function's name. Same rules as variable names.
():parentheses, then a colon at the end of the line
the indented linesthe body: what runs each time the function is called
Guess first

What does this print?

1def say_hi():2    print("Hi!")3 4print("Start")

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.

main.py
1def light(street):2    print("Lighting the lamp on", street)3 4light("Mill Road")5light("Stone Bridge")
Output
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.

main.py
1def deliver(ore, count):2    print(f"Delivering {count} {ore}")3 4deliver("iron", 12)5deliver("gold")
Output
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().

main.py
1def area(width, height):2    return width * height3 4room = area(4, 3)5print(room)6print(area(2, 5) + area(1, 1))
Output
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.

A function that only prints shows something, but gives nothing back. A function without a return returns None.

Guess first

What does the second line of output say?

1def double(n):2    print(n * 2)3 4result = double(5)5print(result)
print(x)return x
Shows x on the screenyesno
Gives x back to the callernoyes
Ends the functionnoyes

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:

main.py
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"))
Output
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:

main.py
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]))
Output
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.

main.py
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)
Output
(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:

main.py
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))
Output
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.

Exercise 1

Lamp label

Write a function label(n) that returns the text Lamp n for the number n.

It should print
Lamp 1
Lamp 12
exercise1.py
1# Write label(n) here2 3print(label(1))4print(label(12))
Output
Press Run or Ctrl+Enter
Exercise 2

Full or not

Finish cart_status(load): return "full" when the load is 10 or more, "empty" when it is 0, and "loading" otherwise.

It should print
full
empty
loading
exercise2.py
1def cart_status(load):2    return "loading"3 4print(cart_status(12))5print(cart_status(0))6print(cart_status(4))
Output
Press Run or Ctrl+Enter
Exercise 3

Total and average

Write summary(loads) that returns two values: the total of the list and its average.

It should print
18 6.0
exercise3.py
1# Write summary(loads) here2 3total, average = summary([4, 8, 6])4print(total, average)
Output
Press Run or Ctrl+Enter

What you learned

  • def name(parameters): defines a function; the body runs only when you call name(arguments).
  • Arguments are matched to parameters in order; a missing one is a TypeError.
  • return ends the function and gives a value back. Without it, a function returns None.
  • print shows a value; return hands it back so the caller can use it.
  • return a, b returns a tuple you can unpack. A docstring says what a function does.