AQA GCSE Computer Science (8525), section 3.2.10 (Structured programming and subroutines (procedures and functions))
Local variables
A local variable is declared inside a subroutine. It usually:
- only exists while the subroutine is running, and
- can only be used inside that subroutine.
def double(number):
result = number * 2 # result is local
return result
print(double(5)) # 10
# print(result) # error: result does not exist here
Why local variables are good practice
- No clashes: two subroutines can use the same variable name without affecting each other.
- Less chance of accidental changes to values used elsewhere.
- Memory is used only while needed.
- The subroutine is self-contained, so it can be reused in other programs.
Global variables
A global variable can be used anywhere in the program. They are harder to track, because any part of the program could change them, so local variables are better.
The structured approach
The structured approach to programming means building a program from separate modules (subroutines), each with a clear job and a well-defined interface. This is called modular programming.
The interface of a subroutine is how it communicates with the rest of the program:
- parameters (data going in),
- return values (data coming out),
- local variables (kept private inside).
A well-documented subroutine says what it needs, what it does, and what it gives back, so other programmers do not need to read its code.
Advantages of the structured approach
- Programs are easier to design, using decomposition.
- Each subroutine can be tested separately.
- Code can be reused.
- Programs are easier to maintain and change.
- Several people can work at the same time.
Example
def get_valid_mark():
mark = int(input("Mark (0 to 100): "))
while mark < 0 or mark > 100:
mark = int(input("Try again: "))
return mark
def grade(mark):
if mark >= 70:
return "A"
return "B or lower"
print(grade(get_valid_mark()))
Common mistake: trying to use a local variable outside its subroutine. It does not exist there, so the program gives an error. Also, do not mix up parameters (listed in the definition) with local variables (created inside).
Exam tip: for "why use local variables" give a specific benefit, such as "the same name can be used in different subroutines without affecting each other".
Check yourself
Where can a local variable be used?
Only inside the subroutine in which it is declared.
Give one reason it is good practice to use local variables.
They prevent accidental changes to other parts of the program, and names can be reused safely.
What is meant by the structured approach?
Building a program from separate modular subroutines with clear interfaces of parameters and return values.