Fundamentals · Lesson 16 of 94

Functions

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

Concept

A function is a named block of code you can run whenever you want by writing its name followed by parentheses. You have been calling functions since your first program: print("hi") runs the code inside print with "hi" as its input. Now you will write your own. def greet(): starts one, the indented block underneath is its body, and greet() runs that body.

Functions exist for two reasons, and both are about people rather than computers. The first is naming: calculate_tax(price) tells a reader what is happening without them reading how. The second is reuse: code that lives in a function is written once and called from many places, so a fix in one place fixes every use. Any time you catch yourself copying a block of code, that block wants to be a function.

Functions: def greet():; print('hi') → greet() → greet() → prints hi, twice
Functions · Figure 1 · Open for full size

Defining a function runs nothing. Python reads the def, remembers the body under the name, and moves on. Only a call executes the body, and when the body finishes, execution jumps back to the line after the call. This jump is worth tracing slowly once: the program does not go top to bottom any more, it goes where the calls send it and comes back.

Functions: Diagram 2
Functions · Figure 2 · Open for full size

Inside a function you can use return to hand a value back to the caller. def square(n): return n * n makes square(4) an expression worth 16, which you can print, store, or pass to another function. A function without a return still returns something: the special value None, which means "nothing". The next lesson goes deep on inputs and outputs; this one is about the shape.

The first line of a body can be a string in triple quotes: the docstring. It says what the function does, in one sentence, and help(your_function) shows it, exactly as it does for the built-ins. Write one for every function whose purpose is not clear from its name alone. Function names follow the same convention as variables, lowercase with underscores, and should be verbs or verb phrases: load_config, send_email, is_valid.

Code

Define, then call. The body runs once per call, and nothing is printed until the first call happens, even though the definition comes first.

# greet.py
def greet():
    print("Hello from a function")

print("before any call")
greet()
greet()
print("after two calls")
Output
before any call
Hello from a function
Hello from a function
after two calls

A function with an input and a return. The result is a value you can use anywhere a value can go.

# square.py
def square(n):
    return n * n

print(square(4))
result = square(9)
print(result + 1)
print(square(square(2)))
Output
16
82
16

Reuse in action. Three lines that were nearly identical become three calls, and the formatting rule lives in one place.

# receipt_lines.py
def line(name, price):
    """Return one receipt line with the price aligned to the right."""
    return f"{name:<12}{price:>7.2f}"

print(line("coffee", 3.5))
print(line("bagel", 2.25))
print(line("juice", 4))
help(line)
Output
coffee         3.50
bagel          2.25
juice          4.00
Help on function line in module __main__:

line(name, price)
    Return one receipt line with the price aligned to the right.

A function with no return gives back None. Printing the result of such a call is the most common surprise in a first week of Python.

# none_return.py
def announce(text):
    print(text.upper())

value = announce("shipping")
print(value)
Output
SHIPPING
None

Try it yourself

Create shapes.py with three functions: area_rectangle(width, height), area_circle(radius) using 3.14159, and describe(name, area) that returns a string like "circle: 78.54". Call them to print the descriptions of a 3 by 4 rectangle and a circle of radius 5. Add a docstring to each and check one with help.

Common mistakes

What's next

You can create your own tools. Next you will see exactly how data goes into a function and comes back out: parameters, arguments, defaults, and return values.

Course overview