OCR H446, section 2.2.1 (c)
The scope of a variable is the part of a program where it can be used.
Local variables
A local variable is declared inside a subroutine. It:
- Can be used only inside that subroutine.
- Is created when the subroutine is called, and ceases to exist when it ends (its lifetime).
- Is separate for each call, including recursive calls.
def double(x):
result = x * 2 # result is local
return result
print(double(4))
print(result) # NameError: result does not exist here
Parameters are also local to the subroutine.
Global variables
A global variable is declared outside all subroutines (in the main program). It:
- Can be read anywhere in the program.
- Exists for the whole time the program runs.
rate = 0.2 # global
def add_vat(price):
return price * (1 + rate) # reads the global
In Python, to change a global from inside a function, you must declare it with global. Otherwise Python creates a new local variable of the same name:
count = 0
def wrong():
count = count + 1 # UnboundLocalError
def right():
global count
count = count + 1
OCR pseudocode uses the keyword global:
global total = 0
procedure addToTotal(n)
total = total + n
endprocedure
Comparing them
| Local | Global | |
|---|---|---|
| Declared | Inside a subroutine | Outside all subroutines |
| Scope | That subroutine only | The whole program |
| Lifetime | While the subroutine runs | While the program runs |
| Memory | Freed when the subroutine ends | Kept all the time |
| Safety | Safer: can't be changed by other code | Riskier: any code can change it |
Why local variables are preferred
- No unexpected changes. Nothing else can alter a local variable, so there are fewer side effects.
- Reusable subroutines. A subroutine that uses only parameters and local variables can be copied to another program (2.1.2 (d)).
- Same names can be reused in different subroutines without a clash.
- Saves memory, because the space is freed after the call.
- Easier to test and debug: you only need to look at the one subroutine.
- Supports recursion: each call has its own copy.
- Teams can work on separate subroutines without name conflicts.
Problems with global variables
- Hard to trace which part of the program changed a value.
- Accidental changes by another subroutine.
- A subroutine that depends on a global can't be reused or tested alone.
- Name clashes in large programs.
- Can make a program harder to maintain.
Advantages of global variables
- Data that is needed throughout the program is available everywhere.
- Easier to write: you don't have to keep passing the data as parameters and returning it.
- Fewer parameters, so subroutine calls can be shorter.
Evaluation: in a small program or a prototype, globals can be a sensible shortcut. As the program grows, the problems above (memory, side effects, testing, maintenance) grow too, so it is better to keep data local and pass it as parameters, by value or by reference (2.2.1 (d)).
When globals are acceptable
- Constants that are used in many places (
VAT_RATE,MAX_ITEMS). - Configuration values read by many parts.
- Some state shared across the whole program, if it's carefully managed.
Worked example
Task: explain what is wrong with this code, and rewrite it using local variables.
total = 0
def add_to_total(n):
global total
total = total + n
add_to_total(5)
add_to_total(3)
print(total)
Problems: add_to_total depends on the global total, and changes it as a side effect. It can't be used for a second running total and any other code might change total.
Better: pass the value in and return the result.
def add(total, n):
return total + n
total = 0
total = add(total, 5)
total = add(total, 3)
print(total) # 8
Now add has no side effects, works for any total, and is easy to test: add(2, 3) is always 5.
Scope example
x = 10 # global
def f():
x = 5 # a NEW local x, hides the global
print(x) # 5
f()
print(x) # 10: the global is unchanged
Exam tip: define both by scope and lifetime. When asked why local variables are better, give specific reasons: no side effects, reusable, less memory, easier to debug. Don't just say "they are safer".
Check yourself
What is the scope of a local variable?
The subroutine in which it is declared. It can't be used outside it.
What is a global variable?
A variable declared outside all subroutines, which can be used anywhere in the program and exists for as long as the program runs.
Give two reasons for using local variables instead of global variables
Any two of: no unexpected changes from other code; subroutines are reusable and testable on their own; memory is freed after the call; names can be reused; supports recursion.
Give a situation where a global is acceptable
A constant used in many places, such as a VAT rate or a maximum size.