Variable Scope (Local, Global, Nonlocal)
Scope determines where a variable can be accessed. Python has Local (inside function), Enclosing (nested function), Global (module level), and Built-in scopes — the LEGB rule.
15 min•By Priygop Team•Updated 2026
Scope Rules
Scope Rules
# Local scope — inside a function
def my_func():
local_var = "I'm local"
print(local_var)
my_func()
# print(local_var) # NameError! Not accessible outside
# Global scope — module level
global_var = "I'm global"
def read_global():
print(global_var) # Can READ global variables
read_global() # I'm global
# Modifying global (use 'global' keyword)
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(f"Counter: {counter}") # 2
# Nonlocal — nested function scope
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(f"x = {x}") # 20
outer()
# Best practice: avoid global variables!
# Pass values as parameters and return results instead.Tip
Tip
Avoid global variables. Pass data as parameters and return results. This makes functions testable, reusable, and easier to debug.
Diagram
Loading diagram…
JavaScript looks outward through the scope chain to find variables
Common Mistake
Warning
Assigning to a variable inside a function creates a LOCAL variable, even if a global with the same name exists. Use 'global x' only if you must modify the global.
Practice Task
Note
(1) Create a function that reads a global variable. (2) Try modifying it without 'global' and observe the error. (3) Use nonlocal in a nested function.