SyntaxStudy
Sign Up
Python Intermediate 9 min read

Scope and Globals

Variable Scope in Python

Local Scope

def my_func():
    x = 10  # local
    print(x)

my_func()
# print(x)  # NameError!

Global Scope

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1

Enclosing Scope (nonlocal)

def outer():
    x = 10
    def inner():
        nonlocal x
        x += 5
    inner()
    print(x)  # 15

outer()
Pro Tip

LEGB rule: Local → Enclosing → Global → Built-in (Python's scope lookup order).