Class 18 - Scoping in Python
Date: October 22, 2026
Skills: 5
Notes (review before class)
Updating Variables
At #level advanced, = can give any variable a new value, even at the top
level of the file (outside any function), and functions can use global. Here
is the sum from Class 15, at the top level:
#level advanced
total = 0
for num in [5, 1, 7, 3]:
total = total + num
- Basic data (numbers, strings, booleans) have no internal structure, so they are stored right in the directory. (Structured data, like lists, are stored in a separate place, the heap: Class 25.)
=on a name that already has a value updates its directory entry.- A
forloop adds its name (num) to the directory, and updates it to each element in turn.
The directory as it runs (each column is one moment):
after total = 0 | loop starts | after total = total + num | next element | ... | loop ends | |
|---|---|---|---|---|---|---|
total | 0 | 0 | 5 | 5 | ... | 16 |
num | 5 | 5 | 1 | ... | 3 |
Try drawing the directory as this runs:
count_long = 0
words = ["here", "are", "some", "words"]
for word in words:
if len(word) > 4:
count_long = count_long + 1
Local and Global Variables
Names defined at the top level are in the global directory; each function call has its own local directory (Class 5).
y = 20
z = 100
def f() -> int:
y = 30 # a new local y: the global y is unchanged
return y
def g() -> None:
global z # in g, z means the global z
z = 200
print(f()) # 30
print(y) # 20
g()
print(z) # 200
- Assigning to a name inside a function creates a local variable, even if a global one has the same name: in the function, the name means the local one (it shadows the global one), and the global one is unchanged.
global z, at the start of a function, makeszthere mean the globalz, so assigning to it changes the global entry (as on Class 17).
Recap (15 mins)
A game keeps track of the best score so far, and of the last score. Read through the program:
#level advanced
best = 0
last = 0
def game_score(rounds: list[int]) -> int:
"""the total points scored over the rounds of one game"""
score = 0
for points in rounds:
score = score + points
return score
def test_game_score():
assert game_score([]) == 0
assert game_score([3, 0, 4]) == 7
def record(score: int) -> None:
"""records score as the last score, and as the best score if it is higher"""
global best
last = score
if score > best:
best = score
record(game_score([5, 6]))
record(game_score([2, 2]))
print(best, last)
score = 50
print(game_score([1]), score)
- What do the two
prints show? - Just before
game_score([5, 6])returns, what arescoreandpointsin its local directory? recordassigns to bothlastandbest: which assignment changes the global directory? What wouldprint(best, last)show ifrecordalso had the lineglobal last?
Class Exercises (40 mins)
-
Given this Python code, predict what will happen and explain why:
y = 100
def outer():
y = 200
def inner():
y = y + 50
return y
return inner()
print(outer())Can you fix the code so that
inner()updates theydefined outside of both functions? -
Given this Python code, predict what will print and explain why:
x = 10
def foo():
x = x + 1
return x
print(foo())Now fix the above code so that it increments the global
x.
Wrap-up (5 mins)
- Python's rules for assignment and scoping determine which variable each use of a name refers to.
- Understanding these rules helps avoid bugs and write clearer code.