← All lessons
Python basics · Lesson 10 of 10

Writing functions

You've been calling functions like print() and len() from the start. Now you'll write your own. A function is a block of code with a name. You write it once, then run it whenever you like by calling its name. It saves repeating yourself, and it lets you think about one small job at a time.

Define one with def (short for define), a name, brackets and a colon, then the indented body. Defining it doesn't run it; calling it does.

def greet():
    print("Hello!")
    print("Welcome to the pond.")

greet()
greet()
Prints
Hello!
Welcome to the pond.
Hello!
Welcome to the pond.

Functions get more useful when you can hand them information. Names in the brackets of a def are parameters: variables that are filled in when the function is called. The values you pass in a call are called arguments.

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

greet("Ana")
greet("Ben")
Prints
Hello, Ana!
Hello, Ben!

return sends a value back to whoever called the function, and ends the function there. The call then stands for that value, so you can store it, print it or use it in a sum.

def area(width, height):
    return width * height

room = area(3, 4)
print(room)
print(area(2, 5) + area(1, 1))
Prints
12
11

Printing isn't returning. print() shows a value on screen for a person; return hands it back to the program so it can be used. A function with no return gives back the special value None, which means "nothing".

def double_print(n):
    print(n * 2)

def double(n):
    return n * 2

x = double_print(5)
y = double(5)
print(x, y)
Prints
10
None 10

Variables made inside a function exist only inside it; they disappear when it returns. This keeps functions from tripping over each other. To get something out, return it.

Here's a small program that puts the whole course together: a function, a loop, a list, a decision and an f-string.

def grade(score):
    if score >= 80:
        return "great"
    elif score >= 50:
        return "pass"
    return "retry"

scores = [91, 47, 66]
for s in scores:
    print(f"{s}: {grade(s)}")
Prints
91: great
47: retry
66: pass

That's the beginner course. Next, Python intermediate covers dictionaries, files, errors and classes, the tools for real programs.

Practice

What does this print? (Separate the lines with spaces.)

def cheer():
    print("Go!")

cheer()
cheer()
cheer()
More info

Quick reference

def name(params):Defines a function. The indented body runs when it's called.
name(args)Calls it. Arguments fill in the parameters in order.
return valueEnds the function and gives the value back to the caller.
NonePython's "nothing". What a function without return gives back.
local variableMade inside a function, gone when it returns.

Related courses