Python Reference ยท Statements and Keywords
The def statement
Reference for Python's def statement: parameters, defaults, keyword-only and positional-only arguments, *args and **kwargs, annotations, docstrings and the mutable default trap.
def defines a function. When Python executes the statement it creates a function object and binds it to the name; the body does not run until the function is called. Functions can take parameters, return values, carry a docstring and type annotations, and be nested inside other functions.
A function without a return statement returns None. Functions are ordinary objects: you can store them in lists, pass them around and attach attributes.
def greet(name, punctuation="!"): return f"Hello, {name}{punctuation}" greet("Ada") # 'Hello, Ada!'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
def name(positional_only, /, normal, *args, keyword_only, **kwargs) -> ReturnType: """Docstring.""" body
| Part | Description |
|---|---|
name |
The name bound in the current scope to the new function object. |
parameters before / |
Positional-only (3.8+): cannot be passed by keyword. |
normal and normal=default |
Passed by position or keyword. After the first parameter with a default, all later ones before * need defaults too. |
*args |
Collects extra positional arguments in a tuple. |
parameters after * or *args |
Keyword-only. |
**kwargs |
Collects extra keyword arguments in a dict. |
-> ReturnType |
Optional annotation; not enforced at run time. |
| docstring | A string literal as the first statement, available as __doc__. |
Return value of a call: whatever return supplies, or None.
Raises (at call time): TypeError for missing, extra, duplicate or wrongly passed arguments.
Usage notes
- Defaults are evaluated once, when
defruns. Never use a mutable object ([],{},set()) as a default; useNoneand create it inside. - Arguments are passed by object reference. The function gets the same object, so mutating a list argument is visible to the caller, while rebinding the parameter name is not.
- Scope. Names assigned in the body are local. Reading outer names works; assigning to them needs
globalornonlocal. - Decorators go on the line above
defand replace the function with the decorator's result. async defdefines a coroutine function, and a body containingyieldmakes a generator function (seeyieldandasync/await).- Annotations are not checked; use a type checker such as mypy. Python 3.14 evaluates annotations lazily (PEP 649), so forward references work without quotes.
- Recursion is limited by the interpreter's recursion limit (see
RecursionError). - A function is created each time
defexecutes, so adefinside a loop or another function builds a new object every time.