Sure! Here's a quick refresher on variable scope in Python:
Variable Scope in Python
1. Local Scope
- Variables defined inside a function are local to that function.
- They exist only while the function is running.
- You cannot access them outside the function.
def func():
x = 10 # local variable
print(x)
func()
# print(x) # Error! x is not defined outside func
2. Enclosing (Nonlocal) Scope
- When you have nested functions, the inner function can access variables from the outer (enclosing) function.
- To modify a variable from the enclosing scope inside the inner function, use the
nonlocal keyword.
def outer():
x = 5
def inner():
nonlocal x
x = 10 # modifies x in outer()
print(x)
inner()
print(x)
outer()
# Output:
# 10
# 10
3. Global Scope
- Variables defined at the top level of a module (outside any function or class) are global.
- Functions can read global variables by default.
- To modify a global variable inside a function, use the
global keyword.
x = 20 # global variable
def func():
global x
x = 30 # modifies the global x
print(x)
func()
print(x)
# Output:
# 30
# 30
4. Built-in Scope
- Python has a built-in namespace with functions like
print(), len(), etc.
- These are searched last if a variable is not found in local, enclosing, or global scopes.
Summary: LEGB Rule
When Python looks up a variable name, it searches scopes in this order:
- Local — inside the current function
- Enclosing — any and all enclosing functions (for nested functions)
- Global — at the module level
- Built-in — Python’s built-in names
Example illustrating LEGB:
x = 'global x'
def outer():
x = 'enclosing x'
def inner():
x = 'local x'
print(x) # prints 'local x'
inner()
print(x) # prints 'enclosing x'
outer()
print(x) # prints 'global x'
If you want me to explain any part in more detail or with examples, just ask!