? Scope of Variables in Python
? Scope of Variables in Python
✅ What is Scope?
The scope of a variable refers to the part of the program where the variable can be accessed or
used.
Example of Scope
Type Description
Area
Variable declared inside a function. Accessible only Inside a specific
L – Local
within that function. function
E– Outer function of a
Variable in the enclosing function (for nested functions).
Enclosing nested one
Variable declared outside all functions. Accessible Entire program (module
G – Global
throughout the program. level)
B – Built-in Predefined names in Python (like print(), len()) Always accessible
def show():
x = 5 # Local variable
print(x)
show()
# print(x) # Error: x is not defined outside the function
2. Global Variable
def show():
print(x) # Accessing global variable
show()
print(x) # Works fine
x = 10
def update():
global x
x = 20
update()
print(x) # Output: 20
outer()
💡 Summary Table
Scope Where it's Defined Where it's Accessible
Local Inside a function Only inside that function
Enclosing Outer function (nested case) Inside inner function
Global Outside all functions Anywhere (with global keyword if needed)
Built-in Predefined by Python Anywhere in the program
📝 Tips
• Use local variables when you only need them inside a function.
• Use global variables carefully to avoid confusion.
• Know when to use the global keyword.
• Understand nested functions and enclosing scope for clarity in advanced problems.