Four places Python looks for a name
When you use a name, Python searches in this order and stops at the first hit:
- Local: names assigned inside the current function.
- Enclosing: names in a function that contains this one.
- Global: names at the top level of the module.
- Built-in:
print,len,sumand the rest.
That is the LEGB rule, and it explains both directions of confusion.
Reading a global from inside a function works without ceremony:
TAX_RATE = 0.18
def with_tax(amount):
return amount * (1 + TAX_RATE) # fine, found at step 3Assigning changes everything
count = 0
def bump():
count = count + 1 # UnboundLocalError
bump()UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueThe reason is precise and worth knowing. When Python compiles the function, it scans the whole body. Because count is assigned somewhere in it, count is marked local for the entire function, including the line that tries to read it before the assignment. The global count becomes invisible inside bump, so the read on the right-hand side has nothing to fetch.
The surprising part is that this happens even when the assignment comes later:
def report():
print(TAX_RATE) # UnboundLocalError
TAX_RATE = 0.05
report() # The error occurs when the function runs.A single assignment anywhere in the body makes this name local throughout the function. Python decides that scope while compiling the function. The UnboundLocalError is raised later, when the function runs and tries to read the local name before it has a value.
global, and why to avoid needing it
count = 0
def bump():
global count
count += 1That works. It also means any function anywhere can now change count, and when the value is wrong you have to read the whole program to find out who changed it. Every additional global roughly doubles the search space when debugging.
Better shapes, in order of preference:
def bump(count):
return count + 1 # take it in, hand it back
count = bump(count)or keep the state in an object, or in a dictionary passed explicitly. Module-level constants in capitals, read but never assigned, are fine and normal; global for mutable state is the thing to avoid.
Mutation slips through without global
totals = []
def record(x):
totals.append(x) # works — no `global` neededNo error, and the list does change. The rule from the previous lesson applies: totals.append(x) does not assign to the name totals, it calls a method on the object the name already refers to. Only assignment triggers the local-name rule.
So totals = [] inside the function would need global, and totals.append(x) does not. That asymmetry catches people who learned the global rule as “you cannot change globals from a function”.
nonlocal, for nested functions
def counter():
n = 0
def increment():
nonlocal n
n += 1
return n
return incrementnonlocal says “the name in the enclosing function, not a new local and not a module global”. Without it, n += 1 would be an UnboundLocalError inside increment. You meet this in closures and decorators, both of which appear later in the course.
Loops and if do not create a scope
Unlike most languages with braces, Python only creates a new scope for a function, a class, or a module. A variable first assigned inside a for or an if is visible after it:
rows = ["a", "b", "c"] # also try an empty list
for row in rows:
last = row
print(last) # An empty list skips the assignment to last.If the loop runs zero times, it never assigns to last. Reading last afterwards raises NameError if the name has no earlier binding. If last already has a value, the old value remains. Initialise it before the loop when later code depends on it.
Shadowing a built-in
list = [1, 2, 3]
list("abc") # TypeError: 'list' object is not callableAssigning to list, dict, sum, id, type or input hides the built-in for the rest of the module. Nothing warns you at the moment you do it; the failure comes later, somewhere else, in code that had every right to expect list to be a type. Add a trailing underscore (list_) or pick a better name.
Free linters catch this in one command: ruff check flags shadowed built-ins, unused names and the loop-variable problems above, and it runs in under a second on a whole project.
Check your understanding
A function reads config on its first line and, twenty lines later, does config = {} in an error branch that has never yet run. Every call now fails on line 1 with UnboundLocalError. Why does an unreached line break the first line?
Pick the one you would defend. Your answer stays private.
Your place and first choices stay on this browser. Classroom credit is recorded separately.
Stuck on something?Ask Divya, your AI tutor