def

Defines a function: a named block of code with parameters that you can call multiple times.

On this page

Example

#
Python
def award(name, exp=10, reason=None):
    """Returns a description of the awarded points."""
    text = f"{name}: +{exp} EXP"
    if reason:
        text += f" ({reason})"
    return text

print(award("Emma"))
print(award("Jack", 25, reason="module completed"))
Resultsaved result, you can check it
Emma: +10 EXP
Jack: +25 EXP (module completed)

Definition and usage

#

The def keyword creates a function. After the name, you give the parameters in parentheses, and after the colon, an indented block of code. You call a function by writing its name with parentheses and arguments.

Parameters can have default values (exp=10). You can pass arguments in order or by name (award(name="Emma", exp=20)), which improves readability when there are many parameters.

The *args notation collects any number of positional arguments into a tuple, and **kwargs collects named arguments into a dictionary. The first line of a function can be a docstring, a string that describes what it does.

Syntax

#
Syntax
def name(param, default=value, *args, **kwargs):
    ...

More examples

#
*args and **kwargs
Python
def summary(*scores, **info):
    avg = sum(scores) / len(scores)
    return f"{info.get('name', 'Student')}: average {avg:.1f} from {len(scores)} tests"

print(summary(80, 95, 70, name="Mia"))
Resultsaved result, you can check it
Mia: average 81.7 from 3 tests
A trap: a mutable default value
Python
def add_task(task, tasks=None):
    if tasks is None:
        tasks = []
    tasks.append(task)
    return tasks

print(add_task("HTML"))
print(add_task("CSS"))
Resultsaved result, you can check it
['HTML']
['CSS']

Good practices

#
  • Do not use mutable default values, like [] or {}. They are created once and shared between calls. Use None instead.
  • Name functions with verbs in snake_case, e.g. calculate_total.

Related entries

#

Spotted a mistake or missing an example? Write to us.