🌐 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.
📚 Types of Variable Scope
Python has four types of variable scope, often remembered by the acronym LEGB:
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
🔍 Local and Global Variables
1. Local Variable
• Declared inside a function
• Exists only while the function is running
def show():
x = 5 # Local variable
print(x)
show()
# print(x) # Error: x is not defined outside the function
2. Global Variable
• Declared outside all functions
• Can be accessed inside and outside functions (EXAMPLE IN NEXT PAGE)
x = 10 # Global variable
def show():
print(x) # Accessing global variable
show()
print(x) # Works fine
3. Modifying Global Variables Inside a Function
To modify a global variable inside a function, use the global keyword:
x = 10
def update():
global x
x = 20
update()
print(x) # Output: 20
4. Enclosing Scope (Nested Functions)
def outer():
x = "outer value"
def inner():
print(x) # Accesses x from outer function
inner()
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.