Lesson 7

Functions — bundling reusable code

A function is a named block of code you can call as many times as you like. Functions keep your code tidy and easy to change.

Defining a function

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

greet("Sam")
greet("Pat")
Hello, Sam! Hello, Pat!

The shape:

return — sending a value back

print just shows something on screen. return hands a value back to whoever called the function, so they can use it:

def add(a, b):
    return a + b

total = add(3, 4)
print(total)              # 7
print(add(10, 20) * 2)   # 60
Rule of thumb Use return when the function computes something. Use print when the function's job is to show information to the user.

Multiple parameters & default values

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

print(greet("Sam"))                  # Hello, Sam!
print(greet("Sam", "Howdy"))         # Howdy, Sam!
print(greet(name="Pat", greeting="Hi"))  # Hi, Pat!  — keyword arguments

A function with a small bit of logic

def grade_for(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    return "F"

for s in [95, 82, 71, 40]:
    print(s, "=>", grade_for(s))
95 => A 82 => B 71 => C 40 => F

Variables inside vs outside a function (scope)

Variables created inside a function exist only inside that function:

def make_message():
    msg = "Hi from inside"
    print(msg)

make_message()
# print(msg)   # would crash — msg doesn't exist out here

Why bother with functions?

Putting it together

def total_with_tax(price, qty, tax_rate=0.20):
    subtotal = price * qty
    tax = subtotal * tax_rate
    return subtotal + tax

cart = [("book", 9.99, 2), ("pen", 1.50, 5)]

for name, price, qty in cart:
    print(f"{name}: £{total_with_tax(price, qty):.2f}")
book: £23.98 pen: £9.00