Chapter 6: Functions
Chapter 6: Functions
Functions are the building blocks of reusable code in Python. They let you package logic into named units that can be called multiple times with different inputs. Mastering functions is essential for writing clean, maintainable data science code.
Writing and Using Functions
Functions encapsulate logic and make your code more organized and reusable.
Basic Function Structure
Every function has a name, optional parameters, a body, and a return value:
Docstrings: Documenting Your Functions
Always document what your function does with a docstring:
Function Arguments
Python supports both positional and keyword arguments, giving you flexibility in how you call functions.
Positional Arguments
Arguments are matched by position:
The order matters! Changing the order changes which parameter gets which value.
Keyword Arguments with Defaults
Arguments with default values can be called by name in any order:
Mixing Positional and Keyword Arguments
You can combine both types, but positional arguments must come first:
Return Values
Functions can return different types of values, or even other functions.
Default Return Value: None
If a function doesn't explicitly return anything, it returns None:
Returning Simple Values
Most functions return a value:
Returning Multiple Values
Return tuples to return multiple values:
Functions Returning Functions
Functions are first-class objects in Python - they can be returned:
Closures: Functions with State
Closures are functions that remember variables from their enclosing scope.
Creating a Closure
Use nonlocal to modify variables from the outer scope:
Multiple Independent Closures
Each closure maintains its own state:
Lambda Functions: Anonymous Functions
Lambda functions are small, unnamed functions defined inline.
Basic Lambda Syntax
When to Use Lambda
Lambdas are best for simple, one-time operations. For anything complex, use regular functions for better readability.
Lambda with Pandas
Lambdas are commonly used with pandas:
You can also use regular functions:
Applying Functions to DataFrames
Functions shine when processing data in pandas DataFrames.
Creating Sample Data
Applying a Function to a Column
Applying Functions to Rows
Use axis=1 to apply a function to each row:
Partial Functions
Partial functions let you "freeze" some arguments of a function, creating a new function with fewer parameters.
Creating Partial Functions
Partial Functions with Data Processing
Advanced Function Patterns
Variable Arguments with *args
Accept any number of positional arguments:
Variable Keyword Arguments with **kwargs
Accept any number of keyword arguments:
Combining *args and **kwargs
Recursive Functions
Functions can call themselves to solve problems recursively:
Fibonacci Sequence
Key Takeaways
- Functions: Encapsulate reusable logic with clear inputs and outputs
- Arguments: Use positional for required params, keyword for optional ones
- Docstrings: Always document what your function does
- Return Values: Functions can return None, single values, tuples, or even other functions
- Closures: Functions that remember their enclosing scope's variables
- Lambda: Use for simple, one-time operations; prefer regular functions for clarity
- Pandas Apply: Essential for transforming DataFrame columns and rows
- Partial Functions: Create specialized versions of general functions
- ***args/kwargs: Accept variable numbers of arguments for flexible functions
Functions are the foundation of code organization in Python. Write small, focused functions with clear purposes, and your code will be easier to understand, test, and maintain.
Quiz
Further Reading
📝 Test Your Knowledge: Chapter 6: Functions
Take this quiz to reinforce what you've learned in this chapter.