Statement

def (functions)

def creates a function: a named block of code you can run again and again with different inputs, and that can return a result.

BeginnerEvery example below runs in your browser. Change the code and press Run.

def name(param1, param2=default, *args, **kwargs): """Optional docstring.""" # body return value

def gives a name to a block of code. Later you run that block by writing the name followed by parentheses, which is called calling the function. Values you pass in the parentheses are arguments; inside the function they arrive as parameters.

Functions keep you from repeating yourself, and they let you split a big program into small pieces with clear names. A function can send a result back with return statement; without it, the function returns None.

One thing surprises nearly everyone: a default value such as items=[] is created once, when Python reads the def, and is shared by every call. Use None as the default for lists and dictionaries.

Parameters

ParameterWhat it is
param
required
A normal parameter. The caller must give a value, by position or by name.
param=default
optional, default the value after =
A parameter with a default value, used when the caller leaves it out. Defaults must come after parameters without one.
*args
optional
Collects any extra positional arguments into a tuple.
**kwargs
optional
Collects any extra named arguments into a dictionary.

Return value

Defining a function creates a function object and gives it the name. Calling it returns whatever return sends back, or None.

Examples

1A simple function

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

greet("Amara")
greet("Jonas")
Output
Hello, Amara!
Hello, Jonas!

2Return a value

Pythoneditable
def price_with_vat(net, rate=0.20):
    return round(net * (1 + rate), 2)

print(price_with_vat(50))
print(price_with_vat(50, 0.24))
print(price_with_vat(net=80, rate=0.10))
Output
60.0
62.0
88.0

rate has a default, so it can be left out. Arguments can also be passed by name.

3Any number of arguments with *args

Pythoneditable
def average(*numbers):
    if not numbers:
        return 0
    return sum(numbers) / len(numbers)

print(average(4, 8, 6))
print(average())
Output
6.0
0

4Named options with **kwargs

Pythoneditable
def make_profile(name, **details):
    print("Name:", name)
    for key, value in details.items():
        print(f"  {key}: {value}")

make_profile("Sofia", city="Madrid", job="nurse")
Output
Name: Sofia
  city: Madrid
  job: nurse

5A docstring and a function that returns two values

Pythoneditable
def min_max(values):
    """Return the smallest and the largest value."""
    return min(values), max(values)

low, high = min_max([7, 2, 9, 4])
print(low, high)
print(min_max.__doc__)
Output
2 9
Return the smallest and the largest value.

Returning several values really returns one tuple, which you can unpack into separate names.

Common mistakes

A list as a default value

The default list is made once and shared by every call, so it keeps growing. Use None and create a new list inside.

Pythoneditable
def add_bad(item, items=[]):
    items.append(item)
    return items

print(add_bad("a"))
print(add_bad("b"))

def add_good(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_good("a"))
print(add_good("b"))
Output
['a']
['a', 'b']
['a']
['b']

Printing instead of returning

A function that only prints gives back None, so you cannot use its result in a calculation.

Pythoneditable
def double_print(x):
    print(x * 2)

def double(x):
    return x * 2

result = double_print(5)
print("result:", result)
print("result:", double(5))
Output
10
result: None
result: 10

Forgetting the parentheses when calling

greet on its own is the function object; greet() runs it. Writing just the name does nothing useful.

Questions people ask

What is the difference between a parameter and an argument?

The parameter is the name in the def line; the argument is the value you pass when you call the function.

Can a Python function return more than one value?

Yes: return a, b returns a tuple, and x, y = f() unpacks it.

What does a function return if there is no return?

None. See return statement.

How do I write a tiny one-line function?

For a short expression you pass to another function, use lambda: sorted(words, key=lambda w: len(w)).

Spotted a mistake on this page? Tell us