Subprogrammes

If you write a 10,000 line programme, you shouldn't have to copy-paste the "Login" logic 50 times. You write it once in a Subprogramme, and call it whenever you need it.

Functions vs Procedures

There is only one difference you need to know for the exam. The difference is the return command.

No Output

Procedure

A procedure just does something (like printing to screen, or clearing a database). It does not return data back.

def SayHello():
    print("Welcome!")
Returns Data

Function

A function performs a calculation and always hands a value back to the main programme using return.

def AddTaxes(price):
    total = price * 1.2
    return total

Local vs Global Scope Inspector

If you create a Local Variable inside a subprogramme, the rest of the programme literally cannot see it. It is destroyed as soon as the function ends. Select an action below to inspect visibility.

Main Programme (Global Code)
global_password = "Admin123"

Output: Admin123
ERROR: 'local_score' is not defined. (It is trapped inside the function!)
Subprogramme Area (Local Scope)
def calculateGame():
    # This variable ONLY exists inside this function
    local_score = 100

    
Output: Admin123 (Globals are visible everywhere)

Passing Arrays as Parameters

If you pass an Array into a Subprogramme, any changes made to the array inside the function will permanently alter the original array globally. Arrays are passed by reference, not by making a temporary copy!

Check Your Understanding

1. What is the explicit difference between a Procedure and a Function?

2. I have declared total_health = 100 on line 1 of my main code. Later, inside a 'TakeDamage' function, I try to print `total_health`. What happens?

Written Exam Scenario (AO2/AO3)

Stretch (Grade 9)

"Write an algorithm for a Function called FindTotal. It must accept an array of integers called scores as a parameter, use a loop to add them all together into a local variable, and eventually return the final total." (6 marks)