01 / 20

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

Global Scope Enclosing Scope (outer function) Local Scope (inner function) x = "global" y = "enclosing" z = "local" inner() can see z, y, x outer() can see y, x module level sees only x

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

Local miss Enclosing miss Global miss Built-in miss NameError found → use it found → use it

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)

Question 2 of 5

Which keyword lets an inner function modify a variable in its enclosing (outer) function?

Question 3 of 5

What error does this code produce?

count = 0 def inc(): count += 1 inc()

Question 4 of 5

In the LEGB rule, which scope does Python search first?

Question 5 of 5

What does this code print?

def outer(): val = "A" def inner(): nonlocal val val = "B" inner() print(val) outer()