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

  1. Functions: Encapsulate reusable logic with clear inputs and outputs
  2. Arguments: Use positional for required params, keyword for optional ones
  3. Docstrings: Always document what your function does
  4. Return Values: Functions can return None, single values, tuples, or even other functions
  5. Closures: Functions that remember their enclosing scope's variables
  6. Lambda: Use for simple, one-time operations; prefer regular functions for clarity
  7. Pandas Apply: Essential for transforming DataFrame columns and rows
  8. Partial Functions: Create specialized versions of general functions
  9. ***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.