Chapters List
- A Mental Model for Programming
- What Happens When a Program Runs
- Programming Languages
- Variables and Data
- Decisions: Conditional Logic
- Repetition: Loops
- Functions: Building Reusable Code
- Data Structures: Organizing Information
- Debugging: Fixing Programs
- How Programs Become Real Software
- Different Types of Programming
- Modern Programming and Software Development
programming
Functions: Building Reusable Code
Learn how functions help break problems into reusable, manageable pieces.
In the previous chapter we saw how loops let us scale repeated work.
As programs grow, another challenge appears:
How do we keep code organized and maintainable?
Functions are one of the most important answers.
What Is a Function?
A function is a named block of code that performs a specific task.
Instead of repeating the same logic in many places, you define it once and call it whenever needed.
Mental model:
A function is a mini-program inside a larger program.
Why Functions Matter
Functions help developers:
- break large problems into smaller parts
- avoid duplication
- improve readability
- test logic in isolation
This is essential for scaling from short scripts to real applications.
Inputs and Outputs
Most functions use:
- parameters (input values)
- return value (output)
Example:
def add(a, b):
return a + b
result = add(4, 7)
Here, a and b are inputs, and the sum is the output.
Function Calls and Flow
sequenceDiagram
participant Main
participant Func
Main->>Func: Call with inputs
Func->>Main: Return result
When a function is called, control temporarily moves to that function, then returns to the caller.
Designing Good Functions
A practical guideline is single responsibility.
A function should do one coherent thing.
Better:
parse_user_input()validate_email()calculate_tax()
Less maintainable:
- one giant function that parses, validates, computes, saves, and logs everything
Small focused functions are easier to test and reason about.
Reuse and Composition
Programs become powerful when functions call other functions.
This creates layered abstractions:
- low-level utility functions
- mid-level domain logic
- high-level workflows
That structure is the foundation of clean codebases.
Key Ideas to Remember
- Functions are reusable units of logic.
- They improve structure, readability, and maintainability.
- Parameters and return values define clear input/output contracts.
- Small single-purpose functions are easier to test.
- Large systems are built by composing many functions.
What Comes Next
Functions organize behavior.
Now we need to organize data just as effectively:
data structures, and why different structures solve different problems.