Skip to contentSkip to navigation

Module 05 · Lesson 01

Functions & Modular Code

Package reusable code with def: give a function parameters, call it with arguments, send results back with return, and document it with a docstring.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Define and call
  • Return a result
  • Local names
  • Follow a call

Name a piece of work

A function is a set of lines with a name. Write it once, then run it whenever you like by calling its name.

  • def

    def greet(name): creates a function. The indented lines under it are its body.

  • Parameters

    Names in the brackets are the inputs. greet("Ana") gives name the value "Ana".

  • return

    return sends an answer back to the line that called the function, and ends it.

  • Call it

    Brackets run it: greet("Bo"). Without brackets, nothing happens.

Functions everywhere

You have used functions since your first line of Python.

  • Built inprint(), len() and round() are functions someone else wrote for you.
  • Game movesjump(), shoot() and collect_coin() each run when a key is pressed.
  • CalculatorsEach button calls one small function that does one sum.
  • WebsitesPressing Send calls a function that checks your message and posts it.

The first line of a function

Every function starts with a line like this. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

define:def means "define a function". It stores the lines below; it does not run them yet.

Write and call functions

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6First function

Define once, call as often as you like.

Your turn: Add a second parameter, mood, and print it in the greeting.

Python
def greet(name):
    print(f"Hi {name}!")

greet("Ana")
greet("Bo")
greet("Cy")
Output
Press Run to see what it prints.

Watch Python jump into a function

Press Step to run one line at a time. Watch Python jump into the function and back out again.

Ready. Press Step to run the first line.

  1. def area(width, height):
  2. result = width * height
  3. return result
  4. room = area(4, 3)
  5. garden = area(5, 2)
  6. print(room + garden)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Does the hi appear?

def f():
    return 3
    print("hi")

print(f())

0 of 6 answered

Common function misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Naming a piece of work

A function is a named block of code that runs when you call it. You have been calling built-in functions since the first lesson: print(), len(), int(). Now you will write your own.

Try it 1: edit me, then Run
def greet():
    print("Hello!")
    print("Welcome to PyLabs.")

greet()
greet()
Output
Press Run to see what it prints.

def starts a function definition, followed by the name, parentheses and a colon. The indented block is the function's body. Defining a function does not run it; it only teaches Python the name. The body runs each time you call the function by writing its name with parentheses, so this program prints the two lines twice. A function must be defined before the line that calls it runs.

Parameters and arguments

Most functions need some input. Names listed inside the parentheses of the definition are parameters. The values you pass in a call are arguments. When the function runs, each parameter refers to the matching argument.

Try it 2: edit me, then Run
def greet(name):
    print(f"Hello, {name}!")

greet("Mina")      # name is "Mina" during this call
greet("Kofi")      # name is "Kofi" during this call
Output
Press Run to see what it prints.

With several parameters, arguments are matched in order: the first argument to the first parameter, and so on. Passing the wrong number of arguments raises TypeError, with a message saying how many were expected.

return sends a result back

print() shows something on the screen, but the rest of the program cannot use what was printed. return hands a value back to the caller, so it can be stored, used in a calculation or passed to another function. This difference is the single most important idea in this lesson.

Try it 3: edit me, then Run
def add(left, right):
    return left + right

total = add(2, 5)
print(total)               # 7
print(add(total, 10))      # 17
Output
Press Run to see what it prints.

return also ends the function immediately; any lines after it in the same path do not run. A function can have several return statements, for example one in each branch of an if.

A function with no return, or a bare return, gives back the special value None. That is why this is a common bug:

Try it 4: edit me, then Run
def shout(word):
    print(word.upper())

result = shout("hi")       # prints HI
print(result)              # None
Output
Press Run to see what it prints.

shout printed its answer instead of returning it, so result is None. As a rule, functions that work something out should return it and let the caller decide whether to print it. Functions whose whole job is to display something, like greet, can print.

Returning several values

return a, b packs two values into a tuple, and the caller can unpack them straight away. This is a tidy way to return related results together.

Try it 5: edit me, then Run
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([7, 2, 9, 4])
print(low, high)           # 2 9
Output
Press Run to see what it prints.

Local variables

Variables created inside a function, including its parameters, are local: they exist only while that call runs and are invisible outside it. Two functions can both use a variable called total without interfering. After the call ends, its local variables are gone; only the returned value survives. The recursion lesson looks at scope in more detail.

Following a call

When Python meets a call such as add(2, 5), it pauses the current line, jumps into the function, sets left to 2 and right to 5, and runs the body. When it reaches return, it jumps back to the paused line, and the call is replaced by the returned value, as if you had written 7 there. Reading code this way, pausing at each call and asking what value will come back, makes even long programs manageable. It is also exactly what the debugger in an editor shows when you step into a function.

Docstrings

A string on the first line of a function body is its docstring. It explains what the function does, what it expects and what it returns. Python stores it, and help(function_name) shows it.

Try it 6: edit me, then Run
def price_with_tax(price, rate):
    """Return price plus tax at the given rate, such as 0.2 for 20%."""
    return price * (1 + rate)
Output
Press Run to see what it prints.

Designing good functions

Give each function one job, and name it with a verb that says what the job is: calculate_total, is_valid_email, format_date. Functions that answer yes or no often start with is_ or has_ and return a bool. Keep functions short enough to read at a glance; if one grows long, part of it probably deserves its own function. Functions can call other functions, which is how small, simple pieces build up into a whole program.

Try it 7: edit me, then Run
def is_even(n):
    return n % 2 == 0

def count_even(numbers):
    count = 0
    for n in numbers:
        if is_even(n):
            count += 1
    return count

print(count_even([3, 8, 10, 7]))   # 2
Output
Press Run to see what it prints.

Reading the last line needs no explanation of how evenness is checked. That is the real power of functions: once a name is trusted, you can stop thinking about the details behind it.

Syntax

The general shape of the statements in this lesson.

syntax.py
def name(param1, param2):
    """What the function does."""
    result = param1 + param2
    return result          # hand the value back; ends the function

value = name(3, 4)         # call with arguments
def nothing(): pass        # no return gives None
return a, b                # several values as a tuple
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A reusable price calculator

Beginner

Write a function that takes a price and a discount percentage and returns the final price rounded to 2 places. Use it for three items and a basket total.

Python
def discounted(price, percent):
    """Return price after taking off percent per cent, rounded to 2 places."""
    return round(price * (100 - percent) / 100, 2)

shoes = discounted(60, 25)
coat = discounted(120, 10)
hat = discounted(15, 0)
print(shoes, coat, hat)
print("Basket:", round(shoes + coat + hat, 2))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The calculation is written once and called three times with different arguments. Because the function returns its result instead of printing it, the caller can add the three prices together. Changing the rounding rule later means editing one line.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Printing instead of returning

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
def square(n):
    print(n * n)

result = square(4) + 1
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 16, then TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Write this instead

def square(n):
    return n * n

result = square(4) + 1

Why it happens

The function prints its answer but returns None, and None cannot be added to a number.

In the real world

Where this shows up in software people use every day.

  1. Converting recipe quantities

    Cooking

    A recipe website lets readers scale a recipe for a different number of people. One small function does the scaling for every ingredient.

    Why Python fits

    The scaling rule lives in one function with a docstring, and the loop calls it for each ingredient. Serving a different number of people changes one argument, not every line.

    Python
    def scale(amount, serves, wanted):
        """Return amount scaled from serves people to wanted people."""
        return round(amount * wanted / serves, 1)
    
    recipe = [("flour (g)", 200), ("milk (ml)", 300), ("eggs", 2)]
    for name, amount in recipe:
        print(f"{name}: {scale(amount, 4, 6)}")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Can a function call itself?

Yes, that is called recursion, and it has its own lesson at the end of this module.

Where should I put my functions?

Define them near the top of the program, before the code that calls them. Python reads the whole def first, so their order among themselves does not matter.

Can I change a variable from outside inside a function?

Reading it works, but assigning to it creates a new local variable. Pass values in as arguments and return results instead; the recursion lesson explains why.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.