Summary
This chapter introduced functions in Python, which are fundamental building blocks for organizing code, enabling reuse, and implementing powerful programming patterns. Functions allow you to encapsulate logic, accept inputs, and return outputs.
Function Definition
Functions are defined using the def keyword followed by the function name and parameters. They can accept arguments and return values using the return statement.
def greet(name): """Greet a person by name""" return f"Hello, {name}!"
result = greet("Alice")print(result) # Hello, Alice!- Functions can have zero or more parameters
- The
passstatement is used as a placeholder for empty functions - Functions are first-class objects: they can be assigned, passed as arguments, and returned
Arguments and Parameters
Basic Argument Types
Parameters are variables in the function definition. Arguments are values passed when calling the function.
def calculate(x, y, operation="add"): if operation == "add": return x + y elif operation == "multiply": return x * y
calculate(5, 3) # Positional argumentscalculate(x=5, y=3) # Keyword argumentscalculate(5, 3, operation="multiply") # Mixing positional and keywordAdvanced Argument Types
- Default arguments: Provide default values for optional parameters
- Position-only arguments (using
/): Must be passed by position - Keyword-only arguments (using
*): Must be passed by keyword - Arbitrary arguments:
*argscollects positional arguments into a tuple,**kwargscollects keyword arguments into a dictionary
def process(x, y, /, operation="add", *, validate=True): """x and y are position-only, operation is regular, validate is keyword-only""" if validate: return operation(x, y) return None
process(5, 3, operation="multiply", validate=False) # Valid# process(x=5, y=3) # TypeError: x and y are position-onlydef sum_all(*args): return sum(args)
def log_info(message, **kwargs): print(f"Log: {message}") for key, value in kwargs.items(): print(f"{key}: {value}")
sum_all(1, 2, 3, 4) # 10log_info("Error", severity="high", code=500)Scope
Python follows the LEGB rule for variable lookup: Local, Enclosing, Global, Built-in.
Local Scope
Variables defined inside a function are local to that function.
def my_function(): x = 10 # Local variable print(x)
my_function() # 10# print(x) # NameError: x is not definedGlobal Scope
Use the global keyword to modify global variables from within a function.
count = 0
def increment(): global count count += 1
increment()print(count) # 1Nonlocal Scope
Use the nonlocal keyword to modify variables in the enclosing (non-global) scope.
def outer(): x = 10 def inner(): nonlocal x x = 20 inner() print(x) # 20
outer()Advanced Concepts
Functions as First-Class Objects
Functions can be assigned to variables, passed as arguments, and returned from other functions.
def add(x, y): return x + y
operation = add # Assign function to variableprint(operation(5, 3)) # 8
def apply(func, x, y): return func(x, y) # Pass function as argument
print(apply(add, 5, 3)) # 8Nested Functions
Functions can be defined inside other functions, providing encapsulation and helper utilities.
def outer(x): def inner(y): return y * 2 return inner(x)
result = outer(5)print(result) # 10Closures
Closures are nested functions that remember and access variables from their enclosing scope, even after the outer function has finished executing.
def create_multiplier(factor): def multiplier(number): return number * factor # factor is captured from outer scope return multiplier
double = create_multiplier(2)print(double(5)) # 10print(double(7)) # 14Lambda Functions
Lambda functions are anonymous functions defined with the lambda keyword. They can take any number of arguments but can only have one expression.
square = lambda x: x ** 2print(square(5)) # 25
operations = { 'add': lambda x, y: x + y, 'multiply': lambda x, y: x * y}print(operations['add'](3, 4)) # 7Function Documentation
Docstrings
Docstrings are string literals that document functions. They’re accessible at runtime via the __doc__ attribute or the help() function.
def calculate_area(length, width): """Calculate and return the area of a rectangle.
Args: length: The length of the rectangle width: The width of the rectangle
Returns: The area of the rectangle """ return length * width
print(calculate_area.__doc__) # Access docstringhelp(calculate_area) # Display help informationBuilt-in Functions
Python provides powerful built-in functions for common operations:
max() and min()
Find the maximum or minimum value in an iterable.
numbers = [3, 1, 4, 1, 5]print(max(numbers)) # 5print(min(numbers)) # 1print(max([], default=0)) # 0 (with default for empty iterable)sorted()
Sort an iterable and return a new sorted list.
numbers = [3, 1, 4, 1, 5]print(sorted(numbers)) # [1, 1, 3, 4, 5]print(sorted(numbers, reverse=True)) # [5, 4, 3, 1, 1]print(sorted("Python")) # ['P', 'h', 'n', 'o', 't', 'y']map()
Apply a function to each item in an iterable.
numbers = [1, 2, 3, 4]squared = list(map(lambda x: x ** 2, numbers))print(squared) # [1, 4, 9, 16]filter()
Filter items from an iterable based on a condition.
numbers = [1, 2, 3, 4, 5, 6]evens = list(filter(lambda x: x % 2 == 0, numbers))print(evens) # [2, 4, 6]