Python Functions
Functions are the primary building blocks for modular, reusable, and maintainable code in Python. By encapsulating logic into discrete, named routines, you reduce code duplication, improve readability, and isolate state.
1. Defining Functions with def
A function in Python is defined using the def keyword, followed by the function name, parentheses containing optional parameters, and a colon. The body of the function is indented.
def calculate_area(length, width):
"""Calculates the area of a rectangle given its dimensions."""
area = length * width
return area
# Calling the function
result = calculate_area(10, 5)
print(result) # Output: 50
- The
returnStatement: Functions exit immediately when areturnstatement is encountered. If no return value is specified (or if the function reaches its end without a return), Python implicitly returnsNone. - Docstrings: The triple-quoted string immediately following the function header serves as documentation, accessible via
help(calculate_area)orcalculate_area.__doc__.
2. Parameters vs. Arguments
Understanding the distinction between parameters and arguments is essential for writing clean APIs:
- Parameters: The variables defined in the function signature (the blueprint).
- Arguments: The actual values passed into the function during a call (the instance data).
Python supports two main ways to pass arguments: Positional Arguments and Keyword Arguments.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
# Positional arguments (order matters)
describe_pet("hamster", "Harry")
# Keyword arguments (order does not matter)
describe_pet(pet_name="Whiskers", animal_type="cat")
3. Default Parameter Values
You can provide default values for parameters by assigning them a value in the function definition. If the caller omits that argument, the default value is used.
def configure_server(host="127.0.0.1", port=8080, debug=False):
print(f"Connecting to {host}:{port} (Debug: {debug})")
# Using all defaults
configure_server() # Output: Connecting to 127.0.0.1:8080 (Debug: False)
# Overriding specific parameters using keyword arguments
configure_server(port=9000, debug=True)
Rule for Parameter Ordering:
Parameters with default values must come after non-default parameters in the function signature. Violating this rule results in a SyntaxError.
# INVALID: Non-default parameter follows default parameter
# def bad_function(a=1, b):
# pass
# VALID: Non-default parameters first, default parameters last
def good_function(b, a=1):
pass
4. The Mutable Default Argument Gotcha
One of the most infamous pitfalls in Python is using mutable objects (like lists, dictionaries, or sets) as default argument values.
Default argument values are evaluated once—at the time the function is defined, not each time the function is called.
def add_item_bad(item, target_list=[]):
target_list.append(item)
return target_list
print(add_item_bad("apple")) # Output: ['apple']
print(add_item_bad("banana")) # Output: ['apple', 'banana'] - SURPRISE!
The Idiomatic Solution:
Use None as the default value and initialize a new mutable object inside the function body.
def add_item_safe(item, target_list=None):
if target_list is None:
target_list = []
target_list.append(item)
return target_list
print(add_item_safe("apple")) # Output: ['apple']
print(add_item_safe("banana")) # Output: ['banana'] - Correct!