Welcome to Modular Programming: Procedures and Functions!

Have you ever tried building a giant, complex castle out of Lego? If you tried to build the whole thing from one single, solid piece of plastic, it would be impossible to change or fix if something went wrong. Instead, you build with smaller, individual blocks that snap together. If one brick is the wrong colour, you just swap that single brick!

Writing computer programs works in the exact same way. Instead of writing one giant, messy block of code thousands of lines long, programmers break their code down into smaller, reusable, bite-sized blocks. This is called modular programming.

Don't worry if this seems new or tricky at first! By the end of these study notes, you will know exactly how to break problems down and build your own reusable mini-programs using procedures and functions.

---

1. What is Modular Programming?

Modular programming is a software design technique where a large computer program is split into smaller, independent, manageable sections called modules or subroutines.

A subroutine is a named, self-contained block of code that performs a specific task. Once written, a subroutine can be executed (or "called") whenever you need it from anywhere in your main program.

Why do we use modular programming?

Breaking a program into subroutines gives programmers four major superpowers:

Decomposition: This means breaking a large, complex problem down into smaller, easier-to-solve chunks. It is much easier to write and solve five small tasks than one massive one.

Code Reusability: You can write a subroutine once and use it over and over again. You don't need to waste time typing the same lines of code ten times!

Maintainability and Debugging: If your code has a bug (an error), modular programming makes it easy to find and fix. You only need to test that specific subroutine rather than searching through thousands of lines of code.

Abstraction: The main program only needs to know what the subroutine does and how to call it—it does not need to worry about the complex inner workings inside the subroutine.

Key Takeaway: Subroutines are like the building blocks of a program. They save time, stop you repeating yourself, and make code much easier to fix.

---

2. The Two Types of Subroutines: Procedures vs Functions

There are two main types of subroutines you need to know: procedures and functions. The difference between them is all about what happens when they finish their work!

A. Procedures

A procedure is a subroutine that carries out a set of instructions to perform an action, but it does not return a value back to the line of code that called it.

Everyday Analogy: Imagine pressing a button to turn on a light switch. The switch performs the action (the light turns on), but the switch doesn't hand you back a calculated number or object.

B. Functions

A function is a subroutine that carries out instructions, calculates an answer, and returns a single value back to the line of code that called it (using the return keyword).

Everyday Analogy: Imagine typing \(7 \times 8\) into a calculator and pressing the equals button. The calculator takes the numbers, works out the answer, and returns the value \(56\) directly back onto your screen so you can use it in your next calculation.

Quick Comparison:

Procedure: Performs an action. Returns nothing back to the program.

Function: Performs a calculation or process. Returns a value back to the program using a return statement.

Key Takeaway: If a subroutine gives a value back to your program to save in a variable, it is a function. If it just carries out an action without passing back a value, it is a procedure.

---

3. Anatomy of a Subroutine: Defining and Calling

To use a subroutine in a textual programming language like Python, there are two distinct steps you must follow:

1. Define it (Write the instructions for the subroutine).

2. Call it (Tell the computer to actually run those instructions).

Step 1: Subroutine Definition

In Python, we use the special keyword def (short for define) followed by the name of the subroutine, parentheses (), and a colon :. All the code that belongs inside the subroutine must be indented (spaced inwards).

Example of a Procedure Definition:
def say_hello():
    print("Hello! Welcome to programming.")

Step 2: Subroutine Call

Writing `def say_hello():` only creates the recipe—it does not cook the meal! To actually run the code inside the subroutine, you must call it by typing its name followed by brackets:

Calling the Procedure:
say_hello()

---

4. Parameters and Arguments (Passing Data In)

Subroutines become even more powerful when you can pass data into them to work with. This is where parameters and arguments come in.

Parameters (The Placeholders)

A parameter is a special variable listed inside the subroutine's definition header. It acts as an empty placeholder waiting to receive a value.

Arguments (The Actual Values)

An argument is the real value, variable, or data that you pass into the subroutine when you call it.

Memory Trick:
Parameter = Placeholder (defined in the `def` line).
Argument = Actual value (passed in during the call).

Putting it all together: Step-by-Step Function Example

Let's look at a function that calculates the area of a rectangle:

Code:
def calculate_area(width, height):
    area = width * height
    return area

# Calling the function and saving the returned value:
room_area = calculate_area(5, 10)
print(room_area)

What happened here?
1. `width` and `height` are the parameters (placeholders in the definition).
2. We called the function with `5` and `10`. These are the arguments (the actual values).
3. The function calculated the area: \(5 \times 10 = 50\).
4. The return keyword sent the value \(50\) back out.
5. The variable `room_area` caught the returned value and stored \(50\)!

Key Takeaway: Parameters are the placeholders inside the `def` header. Arguments are the real values you send in when calling the routine.

---

5. Variable Scope: Local vs Global Variables

When you create a variable in a program, where can it be seen and used? This is called scope.

Local Variables

A local variable is created inside a subroutine. Its scope is local to that specific routine.

• It is born when the subroutine starts running.
• It is destroyed as soon as the subroutine finishes.
• It cannot be accessed or used outside of that subroutine in the main program!

Analogy: Think of a local variable like items inside your personal pencil case. Only you can reach in and use that pencil while you are at your desk; people in another classroom cannot see or use it.

Global Variables

A global variable is declared in the main body of the program, outside of any subroutine.

• It can typically be accessed and read anywhere throughout the entire program file.

Analogy: Think of a global variable like a clock on the school corridor wall. Anyone from any classroom can look up and check the time.

Key Takeaway: Local variables belong only to the subroutine where they were created. Global variables exist across the wider program.

---

6. Common Mistakes to Avoid

Even experienced programmers slip up sometimes! Watch out for these frequent beginner traps:

Trap 1: Confusing `print()` with `return`
The Mistake: Thinking that `print()` sends a value back to your program.
The Fix: `print()` only displays text on the screen for a human to read. The computer program itself cannot save or calculate with something that was only printed. To send data back into memory so a variable can hold it, you must use return!

Trap 2: Defining a subroutine but forgetting to call it
The Mistake: Writing your `def` block and wondering why nothing happens when you press run.
The Fix: A subroutine will sit quietly forever until you explicitly call it by its name with brackets, like `my_subroutine()`.

Trap 3: Trying to access a local variable outside its subroutine
The Mistake: Writing `print(total)` in your main code when `total` was created inside a function.
The Fix: The computer will give you a "variable not defined" error because local variables vanish when the subroutine ends. Pass the value out using `return` instead!

---

7. Chapter Quick Review

Check your understanding with these essential points:

Modular Programming: Splitting code into smaller, independent subroutines.

Decomposition: Breaking down big problems into manageable parts.

Procedure: A subroutine that carries out an action without returning a value.

Function: A subroutine that carries out a task and returns a value using return.

`def`: The Python keyword used to define procedures and functions.

Parameters: Placeholder variables in the subroutine definition.

Arguments: Real values passed into the subroutine during the call.

Local Scope: Variables created inside a subroutine that cannot be seen from outside.