Scopes in Python LEGB Rule is an important Python topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Scopes in Python LEGB Rule solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Scopes in Python LEGB Rule should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Scopes in Python LEGB Rule should be studied as a practical Python lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the python > scopes page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
Scope determines where a variable is accessible. Python uses the LEGB rule to resolve variable names - it searches in this order:
def my_function():
x = 10 # local variable - only exists inside this function
print(x)
my_function() # 10
# print(x) # NameError: name 'x' is not defined
# Each function call gets its own local scope
def counter():
count = 0
count += 1
return count
print(counter()) # 1
print(counter()) # 1 (fresh scope each call)
message = "Hello" # global variable
def greet():
print(message) # can READ global variable
greet() # Hello
# To MODIFY a global variable inside a function, use 'global'
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count) # 2
# Without 'global', Python creates a new local variable
def bad_increment():
count = count + 1 # UnboundLocalError!
When a nested function references a variable from its enclosing function, it creates a closure.
def outer(x):
def inner(y):
return x + y # 'x' is from enclosing scope
return inner
add5 = outer(5)
add10 = outer(10)
print(add5(3)) # 8
print(add10(3)) # 13
# Closure remembers the enclosing scope
def make_counter():
count = 0
def increment():
nonlocal count # modify enclosing variable
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
# Each call to make_counter() creates an independent counter
counter2 = make_counter()
print(counter2()) # 1 (independent)
def outer():
x = 10
def inner():
nonlocal x # refers to outer's x
x = 20
print(f"inner: x = {x}")
inner()
print(f"outer: x = {x}") # x was modified by inner
outer()
# inner: x = 20
# outer: x = 20
# LEGB in action
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # local
inner()
print(x) # enclosing
outer()
print(x) # global
import builtins
# See all built-in names
print(dir(builtins))
# Built-ins are always available
print(len([1, 2, 3])) # 3
print(type("hello")) # <class 'str'>
print(range(5)) # range(0, 5)
# You can shadow built-ins (but don't!)
# list = [1, 2, 3] # now 'list' is a variable, not the built-in!
# list([1, 2]) # TypeError!
# Check if a name is a built-in
print(hasattr(builtins, "print")) # True
print(hasattr(builtins, "myvar")) # False
When studying Scopes in Python LEGB Rule, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Python, Scopes in Python LEGB Rule becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
def review_scopes-in-python-legb-rule():
value = "sample"
if value:
print("Scopes in Python LEGB Rule: normal path is ready")
else:
print("Scopes in Python LEGB Rule: handle the empty path first")
review_scopes-in-python-legb-rule()
items = []
if not items:
print("Scopes in Python LEGB Rule: no data available, show a fallback")
else:
print(items[0])
Memorizing Scopes in Python LEGB Rule without the situation where it is useful.
Connect Scopes in Python LEGB Rule to a concrete Python task.
Testing Scopes in Python LEGB Rule only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Scopes in Python LEGB Rule.
Memorizing Scopes in Python LEGB Rule without the situation where it is useful.
Connect Scopes in Python LEGB Rule to a concrete Python task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Python, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.