7. Functions & Modular Programming
Writing code that works for you again and again
A function is a named, reusable block of code. You define it once, then call it as many times as you need, from anywhere in your program. Functions are the single most important concept in all of programming for writing code that's maintainable, readable, and scalable.
Think of a function like a vending machine. You put in input (money + selection), it processes something, and gives you output (the snack). You don't care about the internal mechanics — you just use the interface.
Parameters & Arguments
Parameters are placeholders defined in the function signature. Arguments are the actual values you pass in when you call it:
Return Values
Functions can send data back to wherever they were called from using `return`:
Scope (Local vs Global)
Scope determines where a variable is accessible. Variables created inside a function are local — they only exist inside that function and are destroyed when the function ends.
Avoid using global variables inside functions. Instead, pass what the function needs as parameters and return what it produces. This makes functions predictable and easy to test.
Recursion Basics
A recursive function is one that calls itself. This sounds paradoxical, but it's a powerful technique for problems that have a naturally recursive structure — like calculating factorials or navigating folder trees.
Every recursive function needs two things: (1) a base case that stops the recursion, and (2) a recursive case that moves toward the base case. Without a base case, you get infinite recursion — the program crashes.
Writing Reusable Code
The goal of a good function is that it does one thing, does it well, and works on any valid input. Here's a comparison of poorly written vs well-written code:
Knowledge Check
Ready to test your understanding of 7. Functions & Modular Programming?