Keywords and Control Flow

def — Function definition

Define a function and bind the resulting function object to a name when the definition executes. Its body normally runs on a later call, not at definition time. Defaults are evaluated once per execution of the definition, so mutable defaults can persist between calls. Decorators transform the function before the final name is bound. Parameters can be positional-only, positional-or-keyword, or keyword-only; annotations do not by themselves validate arguments. A function containing yield is a generator function.

Formal Syntax & Structure

python syntaxpython
def name(parameters):    suite
# With annotations and optional type parameters (3.12+)def name[T](value: T) -> T:    suite

Working Example

Example Snippetpython
def total(price, /, *, quantity=1):    return price * quantity
print(total(7))print(total(7, quantity=3))
Python Reference