← All lessons

Lesson 8 of 18 · about 18 minutes

Functions 🧩

A function packages code you want to reuse. Define it once with def, call it as many times as you like.

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

message = greet("Ada")
print(message)

Parameters and defaults

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

print(power(3))       # 9
print(power(2, 10))   # 1024
print(power(exponent=3, base=2))   # keyword arguments

Returning more than one thing

def min_max(values):
    return min(values), max(values)

low, high = min_max([4, 9, 1])

Docstrings

def area(w, h):
    """Return the area of a rectangle."""
    return w * h
💡 A function without a return gives back None. Print is not the same as return: return hands a value to the caller.

Scope

Variables created inside a function only exist inside it. Pass data in through parameters and out through return.

Your challenge

Write a function is_prime(n) that returns True for prime numbers. Then print the result for 2, 9 and 17 on separate lines.