SDD9 — Scope: Local vs Global
- I can define local variable and global variable, and identify each in a piece of code
- I can explain why a local variable cannot be accessed outside the sub-program it belongs to
- I can explain why modifying a global variable from inside a function requires the
globalkeyword, while reading one does not
- I can point to the exact line where a local variable is created and explain that it stops existing once its sub-program finishes running
- I can point to the exact line where a global variable is declared and explain that it can be read from anywhere in the program
- I can predict the runtime error produced by a function that tries to change a global variable without declaring
globalfirst
def calculateChange(amountPaid, price): return amountPaid - price, what does calculateChange(100, 75) return?Key vocabulary
Where a variable can and cannot be seen
What is scope?
Scope is the region of a program in which a particular variable can be accessed. Every variable belongs to one of two scopes: local scope, tied to a single sub-program, or global scope, spanning the whole program. Understanding scope means being able to say, for any given variable, exactly which lines of code are allowed to read or change it — and just as importantly, which lines are not.
Local variables and local scope
A local variable is created inside a sub-program — either as a formal parameter (as covered in SDD8) or as a variable assigned somewhere in the sub-program's own body. A local variable exists only for as long as that sub-program is running: it is created the moment the sub-program is called, and it is destroyed the moment the sub-program finishes and returns control to whatever called it. This means a local variable's name has no meaning anywhere else in the program — not in the main part of the program, and not inside any other sub-program, even one that runs immediately afterwards.
Global variables and global scope
A global variable is declared outside every sub-program, directly in the main part of the program. Because it exists in global scope, it can be read from anywhere in the program, including from inside any function or procedure, without any special syntax. This is different from local variables, which are invisible outside their own sub-program.
Reading a global variable versus modifying one
Reading a global variable's value from inside a function works with no extra steps. However, changing (reassigning) a global variable from inside a function requires the variable to be declared with the global keyword first, inside that function. Without it, Python assumes any variable that is assigned a new value anywhere inside a function must be a new local variable — and if that same name is also read before being locally assigned within the same function, this produces a runtime error, because Python has already decided the name refers to a not-yet-created local variable rather than the existing global one.
Why this connects to SDD8
Formal parameters, introduced in SDD8, are a special case of local variables: each formal parameter is created fresh every time its sub-program is called, exists only inside that call, and is destroyed once the sub-program finishes — exactly like any other local variable. This is also why giving a formal parameter the same name as a global variable does not cause a clash: inside the sub-program, the local (parameter) version simply takes priority for that name.
Worked examples
discountRate = 0.1
def applyDiscount(price):
discountedPrice = price - (price * discountRate)
return discountedPrice
applyDiscount(75)
print(discountedPrice)discountedPrice is a local variable — it is created inside applyDiscount and only exists while that function is running. discountRate is global, declared outside every function.applyDiscount(75) returns 67.5 correctly. But the final print(discountedPrice) line raises NameError: name 'discountedPrice' is not defined, because discountedPrice was destroyed the moment applyDiscount finished running.global keywordtotalSales = 0
def recordSale(price):
global totalSales
totalSales = totalSales + price
recordSale(75)
recordSale(60)
print(totalSales)global totalSales tells Python that, inside this function, totalSales refers to the existing global variable rather than a new local one — this is what allows the reassignment totalSales = totalSales + price to update the global value permanently.recordSale(75) then recordSale(60), totalSales is 135. Without the global keyword, this exact code would raise UnboundLocalError: local variable 'totalSales' referenced before assignment, because Python would treat totalSales inside the function as a new local variable that has not yet been given a value.def functionA():
total = 10
return total
def functionB():
total = 20
return totaltotal. Because each has its own separate local scope, these are two completely independent variables that just happen to share a name — neither function is aware the other's total exists.functionA() returns 10 and functionB() returns 20, in either order, with no interference between them.itemCount = 5
def sellItem():
itemCount = itemCount - 1
return itemCount
sellItem()
Predict: what happens when sellItem() is called, and explain why in terms of scope.
- Assuming any variable used earlier in the file is automatically accessible everywhere. Only variables declared in global scope (outside every sub-program) have this property — a local variable from one function is not visible even to code written immediately afterwards.
- Forgetting the
globalkeyword when modifying (not just reading) a global variable inside a function. Reading needs nothing extra; reassigning does — this asymmetry is a frequent source of confusion. - Believing two local variables with the same name in different functions will clash or overwrite each other. Each sub-program's local scope is completely independent.
- Confusing formal parameters with global variables. A formal parameter (SDD8) is local to its own sub-program, not global, even though it is set from outside when the sub-program is called.
- Over-relying on global variables instead of parameters and return values. This can make programs harder to test, trace and maintain — a theme picked up again in SDD18's evaluation criteria.
When asked to explain a scope-related error, name the specific rule being broken — "this is a local variable being accessed outside its sub-program" or "this global variable is being modified without the global keyword" — rather than a vague answer like "the variable doesn't work here." Examiners are looking for the precise scope concept, not just recognition that something is wrong.
Task Set A — Core questions
discountRate = 0.1
def applyDiscount(price):
discountedPrice = price - (price * discountRate)
return discountedPrice
Which variable in this code is local?print(discountedPrice) is written after the function has finished running?totalSales = 0
def recordSale(price):
global totalSales
totalSales = totalSales + price
recordSale(75)
recordSale(60)
What is the value of totalSales after both calls?global totalSales were removed?stockLevel set to 40, then defines a function reduceStock(amount) that correctly subtracts amount from the global stockLevel (remember the keyword needed to modify a global variable inside a function). Then call reduceStock(5).stockLevel = 40
def reduceStock(amount):
global stockLevel
stockLevel = stockLevel - amount
reduceStock(5)
discountRate and discountedPrice from Example 1 as your evidence. (3 marks)Task Set B — Extension
price and a function def showPrice(price):. Predict which value is used inside the function, and explain whether this affects the global variable at all.Higher Computing Science → Software Design & Development → SDD9
Double period — this topic pairs naturally with SDD8 and benefits from live demonstration of the UnboundLocalError, which pupils otherwise find abstract.
Suggested timing: 5 min warm-up + vocab · 20 min notes + scope diagram (live-run Example 1's NameError and Example 2's UnboundLocalError in PyCharm/REPL so pupils see the actual tracebacks) · 15 min Example 3 + "now you try" · 40 min Task Set A · Task Set B as homework or extension for early finishers.
Key misconception: pupils often think removing the global keyword just means the change "doesn't happen" silently — it is worth stressing this is a runtime error (UnboundLocalError), not silent failure, since exam mark schemes expect the specific error behaviour.
SQA command words covered: describe, explain, identify, predict.
Extension suggestion: Extension 1 (maintainability) is a light preview of SDD18 — if time is tight, this can be moved to the SDD18 warm-up instead of being covered here.