Reusable behavior
Encapsulate reusable computation behind a descriptive callable.
Python · Const
def defines a named user-defined function, optionally with decorators, parameters, and a return annotation. Its indented body runs when the function is called.
Executing a function definition creates a function object and binds it to the function name in the current namespace. The definition may include decorators, parameters, and an optional return annotation; its indented suite runs when the function is called, not when it is defined.
[decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite| Name | Type | Description |
|---|---|---|
decorators | expressions | Optional decorators applied to the function object. |
funcname | identifier | The identifier receiving the newly created function object. |
parameter_list | parameters | The function's positional, keyword, variadic, and defaulted arguments. |
return_annotation | expression | Optional expression recorded as the function's return annotation. |
suite | statement suite | The indented statements that form the function body. |
The def statement binds a user-defined function object to its name; calling that object produces the function's result.
def creates a callable user-defined function object and binds it to the declared name.def header ends in :, followed by the function body suite.def greet(name: str, greeting: str = "Hello") -> str:
"""Return a greeting for one person."""
return f"{greeting}, {name}!"
print(greet("Ada"))Defines and calls a function with a required parameter, a default value, and a return annotation.
Encapsulate reusable computation behind a descriptive callable.
Expose a stable interface accepting validated or documented arguments.
Separate a script's executable workflow into testable units.
def do?The def statement creates a user-defined function object and binds it to a name. The body is an indented suite that executes when the function is called.
Follow-up: What happens if a def statement appears inside a conditional? The function is created and bound only if execution reaches that branch.
Its syntax permits decorators, a function name, a parameter list, an optional -> expression, and a colon followed by the suite. Parameters describe the arguments accepted by the call.
Follow-up: How can a function accept arbitrary positional and keyword arguments? Use *args and **kwargs in the parameter list.
A function definition does not itself return the result of the function body. Calling the resulting function executes the suite; an explicit return supplies the call result, while falling through produces None.
Follow-up: Can the definition specify a return type? Yes; the optional annotation after -> is stored as metadata and does not enforce runtime type checking.
lambdaasync defclassreturndecoratorsfunction annotations