def function
Defines a reusable function with parameters and an optional return.
def name(param1, param2=default):
return resultThis static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Defines a reusable function with parameters and an optional return.
The 'def' keyword defines a function object and assigns it to a name. In Python, functions are first-class objects, meaning they can be passed as arguments, returned from other functions, and assigned to variables. The function body is defined by indentation (typically 4 spaces). Python executes the code within the function's local scope, following the LEGB (Local, Enclosing, Global, Built-in) rule for variable resolution. Performance-wise, function calls incur overhead due to the creation of frame objects on the stack; for extremely performance-sensitive tight loops, built-ins or list comprehensions may be preferred. A critical edge case involves default arguments: they are evaluated only once at definition time, which causes mutable objects (like lists) to persist across multiple function calls if modified. Functions without an explicit return statement implicitly return None.
Quick reference
Syntax
def name(param1, param2=default):
return result
Inputs
Parameters
See it in practice
Examples
Basic Function with Positional Arguments
def calculate_area(width, height):
return width * height
result = calculate_area(5, 10)
print(result)50
A simple function taking two parameters and returning their product.
Default Parameters and Keyword Arguments
def power(base, exponent=2):
return base ** exponent
print(power(3)) # Uses default
print(power(3, 3)) # Overrides default
print(power(exponent=4, base=2)) # Keyword arguments9 27 16
Functions can define default values for parameters, allowing them to be omitted during calls.
Handling Arbitrary Arguments with *args
def multiply_all(*numbers):
total = 1
for n in numbers:
total *= n
return total
print(multiply_all(2, 3, 4))24
The *args syntax allows a function to accept a variable number of positional arguments as a tuple.
Debug faster
Common Errors
LogicError
Cause: Using a mutable object (like a list) as a default argument. The list is created once at definition and shared across calls.
Fix: Use None as the default value and initialize the mutable object inside the function body.
def add_item(item, box=[]):
box.append(item)
return boxUnboundLocalError
Cause: Trying to assign to a variable in the local scope that has the same name as a global variable without using the 'global' keyword.
Fix: Use the 'global' keyword or pass the variable as an argument.
count = 0
def increment():
count += 1 # Fails because count is treated as localRuntime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Defines a reusable function with parameters and an optional return.
param1: First parameter. param2: Second parameter with optional default.
LogicError: Use None as the default value and initialize the mutable object inside the function body. UnboundLocalError: Use the 'global' keyword or pass the variable as an argument.