Scope in Python
Local, Global & nonlocal
Learn how Python decides which variable you mean depending on where your code lives: inside a function, at the top level, or in a nested closure.
Python
What Is Scope?
Scope is the region of your program where a particular name (variable, function, class) is visible and can be used. If you try to access a name outside its scope, Python raises a NameError.
Why Does Scope Matter?
★ Prevents Bugs
Names stay isolated: changing x inside a function won't accidentally overwrite x elsewhere.
★ Enables Reuse
You can use the same name in different functions without conflict, just like two rooms can each have their own whiteboard.
★ Clarifies Intent
Readers instantly know whether a variable is local helper data or shared state used across the program.
The Three Scopes You Need
The LEGB Rule
L
Local: names assigned inside the current function.
E
Enclosing: names in any enclosing (outer) function, from inner to outer.
G
Global: names assigned at the top level of the module (file).
B
Built-in: names pre-defined in Python such as print, len, range.
Local Scope in Action
def greet():
message = "Hello!" # local to greet()
print(message)
greet() # prints Hello!
print(message) # NameError: message is not defined
Global Scope in Action
total = 0 # global scope
def add(n):
global total # declare intent to modify global
total += n
add(5)
print(total) # 5
nonlocal for Closures
def counter():
count = 0 # enclosing scope
def increment():
nonlocal count # modify enclosing variable
count += 1
return count
return increment
up = counter()
print(up()) # 1
print(up()) # 2
global vs nonlocal
| global | nonlocal | |
|---|---|---|
| Target scope | Module-level (top of file) | Nearest enclosing function |
| Use case | Modify module-wide state | Modify closure / outer-function state |
| Works without nesting? | Yes | No: requires an outer function |
| Creates if missing? | Yes: can create a new global | No: variable must already exist |
How Python Looks Up a Name
How to Determine Scope
1
Locate the assignment. Find where the variable is assigned (=, +=, for x in ..., etc.).
2
Check for keywords. Is there a global or nonlocal declaration for that name in the same function?
3
If assigned in a function with no keyword: it's local to that function.
4
If only read (never assigned): Python searches outward through LEGB until found.
5
If global declared: all reads and writes in that function target the module scope.
Example 1: Reading a Global
color = "blue" # global
def show():
print(color) # no assignment → reads global
show() # prints "blue"
Example 2: Shadowing a Global
color = "blue"
def show():
color = "red" # assignment → creates LOCAL color
print(color) # prints "red"
show()
print(color) # prints "blue" (global unchanged)
Example 3: nonlocal Closure
def make_adder(n):
total = 0
def add():
nonlocal total
total += n
return total
return add
add5 = make_adder(5)
print(add5()) # 5
print(add5()) # 10
print(add5()) # 15
Common Mistakes
✕ Read-then-Assign
Using print(x) before x = 10 in the same function. Python scans the whole function first: any assignment makes x local, so the earlier read fails with UnboundLocalError.
✕ Forgetting global
Writing count += 1 inside a function expecting to update a global count, without writing global count first. This creates a local and immediately errors.
✕ Using global instead of nonlocal
Inside a nested function, using global x when you meant to modify the enclosing function's x. This skips the enclosing scope and targets the module level instead.
Summary Table
| Local | Global | nonlocal | |
|---|---|---|---|
| Created by | Assignment inside a function | Assignment at module level | Assignment in enclosing function |
| Keyword needed to write? | None (default) | global | nonlocal |
| Lifetime | Until function returns | Until program ends | Until enclosing function's closure is garbage-collected |
| Readability | Best: contained | Use sparingly | Good for closures |
Question 1 of 5
What does the following code print?
x = 10
def foo():
x = 20
foo()
print(x)
The assignment x = 20 inside foo() creates a local variable that shadows the global. The global x stays 10.
Question 2 of 5
Which keyword lets an inner function modify a variable in its enclosing (outer) function?
nonlocal tells Python to bind the name to the variable in the nearest enclosing function scope. global would skip straight to module level.
Question 3 of 5
What error does this code produce?
count = 0
def inc():
count += 1
inc()
The += operator implies an assignment, so Python treats count as local. But it tries to read count before assigning it, causing an UnboundLocalError. Fix: add global count.
Question 4 of 5
In the LEGB rule, which scope does Python search first?
LEGB stands for Local → Enclosing → Global → Built-in. Python always starts with the innermost scope: Local.
Question 5 of 5
What does this code print?
def outer():
val = "A"
def inner():
nonlocal val
val = "B"
inner()
print(val)
outer()
nonlocal val inside inner() re-binds the enclosing val to "B". When outer() prints val after calling inner(), it sees the updated value: "B".