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.
Procedure
A procedure just does something (like printing to screen, or clearing a database). It does not return data back.
print("Welcome!")
Function
A function performs a calculation and always hands a value back to the main programme using return.
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.
global_password = "Admin123"
def calculateGame():
# This variable ONLY exists inside this function
local_score = 100
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)
total = 0
FOR i = 0 to scores.length - 1
total = total + scores[i]
NEXT i
RETURN total
ENDFUNCTION
M1: Function definition with array parameter.
M2: A local running total variable initialised to 0.
M3: A FOR loop iterating through the array.
M4: The mathematical addition step referencing the array index.
M5: Returning the local variable.