def
Defines a function: a named block of code with parameters that you can call multiple times.
Example
#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"))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
#def name(param, default=value, *args, **kwargs):
...More examples
#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"))def add_task(task, tasks=None):
if tasks is None:
tasks = []
tasks.append(task)
return tasks
print(add_task("HTML"))
print(add_task("CSS"))Good practices
#- Do not use mutable default values, like
[]or{}. They are created once and shared between calls. UseNoneinstead. - Name functions with verbs in snake_case, e.g.
calculate_total.
Related entries
#- lambda vs deflambda creates a short, anonymous function with one expression, while def defines a named function that can have multiple statements, default values, and a docstring.
- returnEnds a function and returns a value to the place it was called from.
- lambdaA short anonymous function written as a single expression.
- global and nonlocalLet a function change variables from the global scope or from an enclosing function.
- yieldCreates a generator: a function that returns successive values on demand.
- *args and **kwargsCollecting any number of positional arguments into a tuple and keyword arguments into a dictionary, plus unpacking a collection at call time.
- DecoratorsFunctions that wrap other functions and add behavior to them, such as logging or permission checks. Written as @name.
Spotted a mistake or missing an example? Write to us.