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.
# Defining a function def greet(): print('Hello, World!') print('Welcome to programming!') # Calling a function greet() # All the code above runs here greet() # And again here
Parameters & Arguments
Parameters are placeholders defined in the function signature. Arguments are the actual values you pass in when you call it:
# Function with parameters def greet_user(name, language='English'): if language == 'French': print(f'Bonjour, {name}!') elif language == 'Twi': print(f'Maakyé, {name}!') else: print(f'Hello, {name}!') # Calling with arguments greet_user('Ama') # Hello, Ama! greet_user('Jacques', 'French') # Bonjour, Jacques! greet_user('Kofi', 'Twi') # Maakyé, Kofi!
Return Values
Functions can send data back to wherever they were called from using `return`:
def add(a, b): return a + b def calculate_discount(price, percent): discount = price * (percent / 100) final_price = price - discount return final_price # Using return values total = add(10, 25) # total = 35 sale_price = calculate_discount(200, 30) # sale_price = 140.0 print(f'Total: {total}') print(f'Sale price: GHS {sale_price}')
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.
x = 10 # Global variable def my_function(): y = 20 # Local variable print(x) # Can access global x: 10 print(y) # Can access local y: 20 my_function() print(x) # Works: 10 # print(y) # ERROR! y doesn't exist out here
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.
def factorial(n): # Base case — stops the recursion if n == 0 or n == 1: return 1 # Recursive case — function calls itself return n * factorial(n - 1) print(factorial(5)) # 5 * 4 * 3 * 2 * 1 = 120 print(factorial(0)) # 1
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:
# BAD: Does too much, not reusable def process_user_ama(): print('Ama is 25 years old') print('Ama is an adult') # GOOD: Flexible, reusable, predictable def describe_user(name, age): is_adult = age >= 18 status = 'adult' if is_adult else 'minor' return f'{name} is {age} years old and is a {status}.' print(describe_user('Ama', 25)) print(describe_user('Kojo', 15))
Knowledge Check
Ready to test your understanding of 7. Functions & Modular Programming?