Python Book · Chapter 5

Functions

Functions let you name a piece of work, reuse it, and test it on its own. They are the main way programmers keep big programs manageable.

Defining a function

def greet(name):
    print(f"Hello, {name}!")

greet("Ada")
greet("Linus")

def creates the function; nothing runs until you call it. name is a parameter: a variable that gets its value from whatever you pass in when you call the function.

Returning a value

print shows a value on screen. return hands a value back to the code that called the function, so it can be stored or used:

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

room = area(4, 5)
print(room)            # 20
print(area(2, 3) + 1)  # 7

A function stops as soon as it reaches return. A function without a return gives back None.

Default and keyword arguments

def power(base, exponent=2):
    return base ** exponent

power(5)               # 25
power(2, 10)           # 1024
power(exponent=3, base=2)  # 8

Parameters with defaults are optional. Naming arguments when you call a function makes the call easier to read, and lets you pass them in any order.

Scope

Variables created inside a function only exist inside that function:

def make_total():
    total = 10
    return total

make_total()
print(total)  # NameError: name 'total' is not defined

This is a feature. Each function has its own workspace, so functions do not accidentally overwrite each other's variables. Pass data in through parameters and get it out with return.

Docstrings

A string on the first line of a function describes what it does. Editors show it when you hover over the function, and help(area) prints it.

def area(width, height):
    """Return the area of a rectangle."""
    return width * height

Exercises

1. Maximum of three

Write max_of_three(a, b, c) without using the built-in max.

Show answer
def max_of_three(a, b, c):
    biggest = a
    if b > biggest:
        biggest = b
    if c > biggest:
        biggest = c
    return biggest

2. Is it prime?

Write is_prime(n) that returns True if n is a prime number. Then use it to print every prime below 50.

Show answer
def is_prime(n):
    if n < 2:
        return False
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d += 1
    return True

for n in range(50):
    if is_prime(n):
        print(n)

You only need to test divisors up to the square root of n: if n had a factor bigger than that, it would also have one smaller.

3. print or return?

Why does this print None on the last line?

def double(x):
    print(x * 2)

result = double(4)
print(result)
Show answer

double prints 8 but never returns anything, so result is None. Change print(x * 2) to return x * 2.