PythonFunctionsBeginner

def function

Defines a reusable function with parameters and an optional return.

Review the syntaxStudy the examplesOpen the coding app
def name(param1, param2=default):
    return result

This 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

param1 (optional)Any · First parameter.
param2 (optional)Any · Second parameter with optional default.

See it in practice

Examples

1

Basic Function with Positional Arguments

def calculate_area(width, height):
    return width * height

result = calculate_area(5, 10)
print(result)
Output:
50

A simple function taking two parameters and returning their product.

2

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 arguments
Output:
9 27 16

Functions can define default values for parameters, allowing them to be omitted during calls.

3

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))
Output:
24

The *args syntax allows a function to accept a variable number of positional arguments as a tuple.

Debug faster

Common Errors

1

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 box
2

UnboundLocalError

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 local

Runtime support

Compatibility

Python 3.8+

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.