Skip to content
LumenaryAcademy
Start 55 min

Functions

Name an idea once and use it everywhere. Parameters, return values, scope, and breaking a problem into pieces.

Code tested · 8AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Computer Scientist, Margaret · The Experimenter, Gideon · The Verifier

MotivationH

Naming an idea

You have been using functions since your first program. print, len, type, round and range are all functions: each one wraps up a piece of work behind a name, so you can use it without thinking about how it is done. Nobody who writes len("Accra") worries about how Python counts the letters.

Now you'll write your own. Here is why it matters. In Decisions and loops you met the leap-year rule:

python
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0

Imagine a calendar program that needs this test in six different places. You could copy the line six times, but then a typo in one copy is a bug that is hard to find, and if the rule ever needed changing you would have to find and fix every copy. Worse, a reader who meets the line has to stop and decode it each time.

A function solves all three problems at once. You write the rule once, give it a name, and then write is_leap(year) wherever you need it. The program becomes shorter, it has one place to fix, and it reads like a sentence: if is_leap(year):. That is the deepest reason functions exist: they let you name ideas.

IntuitionH

A machine with a name

A function is like a machine: you put something in, it does its work, and it hands something back.

7square(x)return x * x495, 2rectangle_area(w, h)return w * h10
Two function machines. Values go in as arguments; the function's body does its work; one value comes back out as the result of the call.

Analogy, not a formal construction

A function is like a recipe card in a family cookbook, titled "Jollof rice for N people". The card is written once, with a blank, N, for the number of guests. Each time someone cooks from it they fill in the blank (6 for a family dinner, 40 for a wedding), follow the steps, and hand over the dish. The blank is a parameter, the number filled in is an argument, following the steps is calling the function, and the dish handed over is the return value.

This is very close to the idea of a function in mathematics, where f(x)=x2f(x) = x^2 gives one output for each input (see Functions in Lumenary Math). Python's functions are more general: they can take several inputs, or none, and they can also do things, such as print, besides giving back a value.

DefinitionsH

Definitions

Definition— function definition

A function definition starts with def, then the function's name, then its parameters in parentheses, then a colon. The indented block below it is the body: the steps carried out each time the function is used.

Definition— call and argument

A call runs a function: you write its name followed by parentheses containing arguments, the actual values for this particular use, as in square(7). Parameters are the names in the definition; arguments are the values in the call.

Definition— return value

A return statement ends the call immediately and hands a value back to wherever the function was called. The call expression then stands for that value. A function that finishes without reaching a return gives back the special value None, which means "no value".

Worked examplesH

Writing your first functions

Here is a complete function and three calls:

python
def square(x):
    return x * x

print(square(7))                    # 49
print(square(3) + square(4))        # 9 + 16 = 25
side = 1.5
print(square(side))                 # 2.25

It is worth knowing exactly what happens during a call such as square(3) + square(4):

  1. Python evaluates the argument, 3.
  2. It makes the parameter x refer to 3, inside a fresh space belonging to this one call.
  3. It runs the body. return x * x computes 9 and hands it back.
  4. The call square(3) is replaced by 9, and Python moves on to square(4) the same way. Finally it adds 9 + 16.

Defining a function does not run its body; it only teaches Python the new name. The body runs each time the function is called, and that can be zero times, once, or a million times.

Functions can take several parameters, separated by commas. Arguments are matched to parameters by position, or by name if you write them as keyword arguments:

python
def rectangle_area(width, height):
    return width * height

rectangle_area(5, 2)                  # width=5, height=2
rectangle_area(height=2, width=5)     # same thing, by name

A function can contain any code you like: decisions, loops, other function calls. It can also have several return statements; whichever is reached first ends the call.

python
def square(x):
    return x * x

def is_leap(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

def larger(a, b):
    if a >= b:
        return a
    return b            # only reached when a < b

print(square(7), square(3) + square(4))
print(is_leap(1900), is_leap(2000), is_leap(2024), is_leap(2026))
for y in range(2020, 2031):
    if is_leap(y):
        print(y, "is a leap year")
print(larger(12, 30), larger(-1, -5))
print(larger(square(4), square(-5)))   # calls inside calls
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

In the last line, Python evaluates the arguments first, square(4) is 16 and square(-5) is 25, and only then calls larger(16, 25).

ExplanationH

Returning is not printing

This is the single most important idea in the lesson, and the most common source of confusion for beginners. Look at these two functions:

python
def show_double(x):
    print(x * 2)

def double(x):
    return x * 2

Called on their own in a Run box, both seem to "give" 10 for an argument of 5, because both make 10 appear. But they are completely different:

  • show_double prints 10 to the screen and then gives back None. The 10 went to the human reading the output, and the rest of the program never gets it.
  • double returns 10 to the code that called it, and prints nothing. The program can store it, add to it, or pass it to another function.
python
def show_double(x):
    print(x * 2)

def double(x):
    return x * 2

a = double(5)
print("a is", a, "and a + 1 is", a + 1)

b = show_double(5)          # prints 10 as a side effect...
print("b is", b)            # ...but b is None
print(type(b))
# b + 1 would fail with a TypeError: you can't add None and an int
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The rule of thumb professional programmers follow: a function that computes something should return it, and let the caller decide what to do with it, whether that is printing, saving or using it in further calculation. Keep printing for the outer layer of a program, the part that talks to people. A function that returns is like a good colleague who hands you the report; a function that only prints is like one who reads the report aloud and then throws it away.

ExplanationH

Scope: what a function can see

Each call to a function gets its own private space for names. Parameters, and any variable assigned inside the body, are local to that call: they are created when the call starts and disappear when it ends. Names assigned at the top level of the program, outside any function, are global.

Definition— scope

The scope of a name is the part of the program where it can be used. A local name can be used only inside its function's body, during that call. A function can read a global name, but an assignment inside a function creates or changes a local name, even if a global name is spelled the same way.

python
rate = 0.15                         # a global variable

def with_tax(price):
    tax = price * rate              # reads the global rate; tax is local
    return price + tax

print(with_tax(200))
# print(tax) here would be a NameError: tax only existed during the call

count = 10
def add_one(count):                 # this parameter is a new, local count
    count = count + 1
    return count

result = add_one(count)
print("global count:", count, " result:", result)
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The global count is still 10: the function changed only its own local count. This separation is a feature. It means you can understand a function by reading just the function, without worrying that it secretly changes variables elsewhere, and two functions can both use a name like total without interfering.

There is one confusing case. If a function assigns to a name anywhere in its body, that name is local for the whole body. So this fails:

python
total = 0
def add(x):
    total = total + x    # UnboundLocalError: the local total has no value yet

Python has a global statement to force the global meaning, but experienced programmers rarely use it. The clean solution is the one shown throughout this lesson: pass in what a function needs as parameters, and return what it produces.

Worked examplesH

Docstrings and default values

A string written as the very first line of a function body is its docstring: documentation that Python stores with the function. Calling help(name) displays it, and code editors show it when you hover over a call. By convention it is written in triple quotes """…""", which may span several lines, and it says what the function does, what it expects and what it returns, not how.

A parameter can also have a default value, used whenever the caller leaves that argument out. Parameters with defaults must come after those without.

python
def greet(name, greeting="Hello"):
    """Return a greeting for name, such as 'Hello, Ana!'."""
    return f"{greeting}, {name}!"

greet("Ana")                      # 'Hello, Ana!'
greet("Wanjiru", "Habari")        # 'Habari, Wanjiru!'
greet("Li", greeting="Nǐ hǎo")    # 'Nǐ hǎo, Li!'

You have already used defaults without knowing it: print has a parameter end whose default is a new line, which is why print(n, end=" ") in the last lesson changed it to a space. And round(3.14159) gives 3, while round(3.14159, 2) gives 3.14, because the number of digits defaults to none.

Worked examplesH

Breaking a problem into functions

Big problems become manageable when you split them into small functions, each with one clear job, which call one another. This is called decomposition, and it is how all large programs are built.

Example— Which day of the year is it?

Problem: given a date such as 1 March 2024, say which day of the year it is (the 61st, since January has 31 days and February 2024 has 29), and refuse dates that don't exist, such as 30 February.

Instead of writing one long block of code, start from the top and assume the helpers you wish you had:

  • days_in_month(month, year): how many days that month has. It needs to know about leap years, so it will call is_leap(year).
  • is_valid_date(day, month, year): whether the date exists. It can call days_in_month.
  • day_of_year(day, month, year): add up the days in all the earlier months, then add day.

Each function is short enough to check by eye, and each can be tested on its own before you rely on it.

python
def is_leap(year):
    """Return True if year is a leap year in the Gregorian calendar."""
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

def days_in_month(month, year):
    """Return the number of days in month (1 to 12) of year."""
    if month == 2:
        if is_leap(year):
            return 29
        return 28
    if month == 4 or month == 6 or month == 9 or month == 11:
        return 30
    return 31

def is_valid_date(day, month, year):
    """Return True if day/month/year is a real date."""
    return 1 <= month <= 12 and 1 <= day <= days_in_month(month, year)

def day_of_year(day, month, year):
    """Return 1 for 1 January, 2 for 2 January, ..., 365 or 366 for 31 December."""
    total = 0
    for m in range(1, month):
        total += days_in_month(m, year)
    return total + day

print(day_of_year(1, 3, 2024))      # 61
print(day_of_year(1, 3, 2026))      # 60
print(day_of_year(31, 12, 2024))    # 366
print(is_valid_date(30, 2, 2024), is_valid_date(29, 2, 2024), is_valid_date(29, 2, 2026))
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The order in which the functions were written is worth copying. You start from the function you actually want, day_of_year, and write it as if its helpers already existed. Some programmers call this wishful thinking, and it is a serious technique: it lets you think about one level of the problem at a time. Then you write each helper the same way, until every helper is simple enough to write directly. Finally you test from the bottom up: check is_leap on a few years first, then days_in_month, then the rest, so that when something goes wrong you know which small piece to look at.

Notice the chain of calls: day_of_year calls days_in_month, which calls is_leap. When is_leap returns, control goes back to days_in_month exactly where it left off, and when that returns, back into the loop in day_of_year. Python keeps track of this chain of unfinished calls automatically; you'll see how in Recursion and divide and conquer, where a function calls itself.

ExplanationH

Functions as a way to name ideas

Good programmers use functions even for code that runs only once, because the name explains the code. Compare if 1 <= month <= 12 and 1 <= day <= days_in_month(month, year): with if is_valid_date(day, month, year):. The second says what is being checked; you look inside only if you need to know how.

Some habits that make functions good to use:

  • One job each. If you need the word "and" to describe what a function does, consider splitting it.
  • Names that say what they mean. Verbs for actions (send_reminder), nouns for values (day_of_year), and is_ or has_ for yes-or-no questions (is_leap).
  • Inputs in, result out. A function that depends only on its arguments and only returns a value, without printing or changing anything else, is called a pure function. Pure functions are the easiest to understand and to test, since the same arguments always give the same result. You'll test functions like these in Finding and fixing mistakes.

Professional software is built in exactly this way, out of many thousands of small, named functions, grouped into modules and libraries. Python's standard library is a huge collection of tested functions you can use with import: after import math, you can call math.sqrt(2) or math.gcd(84, 36) without knowing how they work inside. Somebody named those ideas once, carefully, and millions of programs use them.

Note

Functions are values too. After def square(x): ..., the name square refers to a function object, and you can pass it to another function like any other value. For instance, max(-7, 3, 5, key=abs) returns -7, because it compares the numbers by their absolute values using the built-in function abs. You'll use this idea to sort things by any rule you like in Searching and sorting.

Common misconceptionsH

Common mistakes

Misconception

Forgetting the parentheses. print(square) doesn't call the function; it prints a description of the function itself, something like <function square at 0x...>. To call it, you need parentheses and arguments: square(7).

Misconception

"My function printed the answer, so it returned it." Printing shows a value to a person; returning gives it to the program. A function with no return gives back None, and using that result later causes errors such as TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'.

Misconception

"The argument's name must match the parameter's name." It doesn't. In square(side), the parameter x simply refers to the same value as side during that call. The names are independent.

Misconception

Code after return. return ends the call at once. Any lines after it in the same block never run.

Exercises

Exercises

In the Python exercises, the checker calls your function with many different arguments, so make sure it returns its answer rather than printing it.

1. Functions

Warm-upComputational

What is the value of result after this code runs?

def triple(x):
    print(x * 3)

result = triple(4)
Choose one

2. Functions

CoreComputational

What does this program print?

def f(x):
    return x + 3

def g(x):
    return f(x) * 2

print(g(f(1)))

3. Functions

CoreComputational

What does this print?

score = 50

def bonus(score):
    score = score + 10
    return score

new_score = bonus(score)
print(score, new_score)
Choose one

4. Functions

Warm-upComputational

Given

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

which call returns "Olá, Ana!"? Choose all that do.

Choose all that apply

5. Functions

Warm-upComputational

Write a function is_leap(year) that returns True if year is a leap year in the Gregorian calendar and False otherwise. Rule: divisible by 4, except years divisible by 100, except years divisible by 400.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

6. Functions

CoreComputational

Write two functions:

  • count_divisors(n) returns how many whole numbers from 1 to n divide n exactly (for n ≥ 1). For example, count_divisors(12) is 6, because 1, 2, 3, 4, 6 and 12 divide 12.
  • is_prime(n) returns True if n is prime and False otherwise. A prime has exactly two divisors: 1 and itself. Make is_prime call count_divisors.
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

7. Functions

CoreComputational

Write greeting(name, language="en") that returns a greeting:

  • "en": "Hello, Ana!"
  • "es": "¡Hola, Ana!"
  • "sw": "Habari, Ana!"
  • any other language code: fall back to English.

The parameter language must have the default value "en", so that greeting("Ana") works.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

8. Functions

StretchComputational

The starter gives you is_leap and days_in_month from the lesson. Write month_of_day(n, year) that returns the month number (1 to 12) containing the n-th day of year. For example, day 60 of 2024 is 29 February, so month_of_day(60, 2024) is 2; but day 60 of 2026 is 1 March, so month_of_day(60, 2026) is 3. You may assume n is a valid day of that year.

Use days_in_month: don't write out the month lengths again.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Further reading and resources