In Python, scope is the region of a program where a variable is recognized and can be used. Python follows the LEGB rule to find variables:
L → Local E → Enclosing G → Global B → Built-in
print, len).When you use a variable name, Python searches in this order: Local → Enclosing → Global → Built-in.
global keyword allows you to modify a global variable from inside a function.nonlocal keyword allows you to modify a variable from the enclosing (outer) function instead of creating a new local variable.A variable created inside a function belongs to the function’s local scope and cannot be accessed outside.
def my_func():
x = 10 # local variable
print("Inside function:", x)
my_func()
# print(x) # ❌ Error: x is not defined outside
A variable created at the top level of the script is global and can be read inside functions.
x = 100 # global variable
def my_func():
print("Inside function:", x)
my_func()
print("Outside function:", x)
In nested functions, the inner function can access variables defined in the outer function (enclosing scope).
def outer():
y = "outer variable"
def inner():
print("Accessing:", y) # enclosing scope
inner()
outer()
Use global to modify a global variable from inside a function.
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
Use nonlocal in nested functions when you want to modify a variable from the enclosing function.
def outer():
num = 10 # enclosing variable
def inner():
nonlocal num # modify enclosing variable
num += 5
print("Inner:", num)
inner()
print("Outer:", num)
outer()
Inside function: 10. Trying to use x outside the function raises a NameError.Inside function: 100 and Outside function: 100.inner() read y from outer(), printing Accessing: outer variable.global example changes the global count from 0 to 1.nonlocal example changes num in the enclosing function: first prints Inner: 15, then Outer: 15.global when a truly shared value is needed across the whole module (for example, a basic global counter or configuration flag).nonlocal in nested functions, especially in closures, when the inner function should update a value defined in the outer function.global whenever possible.global and nonlocal carefully and only when really needed.nonlocal.global variable to keep track of how many times a function has been called.global from the counter example and see the UnboundLocalError you get.print, uses a global name, an enclosing name, and a local name).