Category: python
The LEGB Lookup Order
Published on 27 Oct 2026
Explanation
Python resolves names through Local, Enclosing, Global, and Built-in scopes, in that order.
Code:
name = 'Global'
def show():
name = 'Local'
print(name)
show()
print(name)
Explanation
A name assigned inside a function is local by default and is not automatically available outside it.
Code:
def calculate():
result = 100
print(result)
calculate()
Explanation
A nested function can read names from its enclosing function when those names are not local to the inner function.
Code:
def outer():
message = 'Outer'
def inner(): print(message)
inner()
outer()
Explanation
Functions can read module-level names. Assignment inside a function creates a local binding unless global is declared.
Code:
language = 'Python' def show_language(): print(language) show_language()
Explanation
Names such as len(), print(), and sum() are available through built-in scope. Avoid naming variables after built-ins.
Code:
def total(values): return sum(values)
print(total([10, 20, 30]))
print(len('Python'))