The LEGB rule in Python defines the order in which variable names are resolved (i.e., how Python searches for a variable’s value).
๐ LEGB Rule
L → Local
Names assigned inside a function. Python looks here first.
def func():
x = 10 # Local
print(x)
E → Enclosing
Names in the local scope of any enclosing functions (for nested functions).
def outer():
x = 20 # Enclosing
def inner():
print(x) # Found in enclosing scope
inner()
G → Global
Names defined at the top-level of a script or module.
x = 30 # Global
def func():
print(x)
func()B → Built-in
Names preassigned in Python, like len, range, print.
print(len("CLCODING")) # Built-in
✅ Summary of LEGB Resolution Order:
- Local
- Enclosing
- Global
- Built-in




0 Comments:
Post a Comment