Legends ofPythos
Claim your name
Writing Real Programs

Functions that do real work

Lesson 1 of 16

Watch the lesson5:32 · with Sigrid
Mental model: Think of a function as a vending machine. You put in specific inputs (money and button press), it performs internal actions you cannot see, and hands back exactly one result. If the slot you pick is empty, it hands back a 'sold out' message instead of a snack.
Why this matters: Real programs are full of machines like this. A till needs to clamp prices so no discount goes below zero. A server needs to validate email addresses before saving them. These functions do the heavy lifting silently, keeping your main logic clean.

Docstrings

def calculate_area(width, height):
    """Return the area, in square metres."""
    return width * height

print(calculate_area.__doc__)
A docstring is just a string as the first line inside a function.
Docstrings use triple quotes. They do not run, but they tell other humans (and tools) what your function does and how to call it. Python keeps the docstring in calculate_area.__doc__, so the last line above prints it. If you forget docstrings, future-you will stare at the code wondering if width is in centimetres or metres.

Returning early

def validate_age(age):
    if age < 0:
        return 'invalid'
    if age == 0:
        return 'newborn'
    return 'ok'
Return as soon as you know the answer. No need to check every case.
An if block that contains a return stops the function immediately. Code after it never runs for that input path. This keeps logic flat and easy to read, avoiding deep nesting of else blocks.

Functions calling functions

def is_even(n):
    return n % 2 == 0

def count_evens(numbers):
    total = 0
    for num in numbers:
        if is_even(num):
            total += 1
    return total

print(count_evens([1, 2, 3, 4]))
count_evens reuses is_even. Each function has one job.
Small functions are easier to test and reuse. If a function is doing two different things, split it into two. Name each function for what it does: format_price, not do_thing.

Your turn

0 of 3 solved

Exercise 1

+30 XP
Write a function called clamp(value, low, high).

It should return the value kept within bounds:
  • If value is less than low, return low.
  • If value is greater than high, return high.
  • Otherwise, return value unchanged.
Add a docstring explaining what it does.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+30 XP
Write a function called format_price(amount).

It should:
  • Return the string 'free' if amount is exactly 0 (use an early return).
  • Otherwise, format the number as two decimal places with a dollar sign in front, like $12.50.
Inside an f-string, :.2f after a value shows it with exactly two decimal places: f'{7:.2f}' gives '7.00'.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+30 XP
Write two functions:
  1. is_valid_email(email) - returns True if the text contains exactly one '@' and at least one '.' after that '@'. Otherwise False.
  2. filter_emails(users) - takes a list of dictionaries, each with an 'email' key. Returns only the emails (as text) where is_valid_email is True.
email.split('@') cuts the text at every '@', so an address with exactly one '@' gives a list of exactly two parts: the part before it and the part after it.
Write your Python here.

Run your code to check it against the tests.