Course contentsShow
← Computer Science
Lesson 194 of 2,8725. Functions and ModularityFree lesson

Function Composition Basics

Understanding how to combine simple functions to create more complex functionality.

Function Composition Basics

What you'll learn: How to combine simple functions together to build more powerful, complex operations.


The Core Idea

Function composition means using the output of one function as the input to another function. Instead of writing one giant, complicated function, you break your problem into smaller pieces, write simple functions for each piece, and then chain them together.

Think of it like an assembly line: one worker adds wheels to a toy car, the next worker adds the body, and the final worker paints it. Each worker (function) does one job well, and the product flows from one station to the next.

Why Compose Functions?

When you follow the Single Responsibility Principle (which you just learned), each function does one thing well. But real programs need to do many things! Composition is how you connect these focused functions to solve bigger problems.

A Simple Example

def double(x):
    return x * 2

def add_five(x):
    return x + 5

# Using composition: feed the result of one into another
result = add_five(double(3))  # First double(3) → 6, then add_five(6) → 11

Here, double(3) executes first, returning 6. That 6 immediately becomes the input to add_five, giving us 11.

Order Matters

option_a = add_five(double(3))  # (3 * 2) + 5 = 11
option_b = double(add_five(3))  # (3 + 5) * 2 = 16

The sequence changes the result! Read from the inside out: the innermost function executes first.

Key Takeaway: Function composition lets you build complex functionality by chaining simple, focused functions together—making your code modular, readable, and reusable.