Python Variable Scope
1. Local Scope
def show_value():
x = 10 # Local variable
print(x)
show_value()
# print(x) # NameError: x is not definedLocal variables exist only within the function where they are declared.
2. Global Scope
x = 20 # Global variable
def display():
print(x)
display()
print(x)Global variables are accessible throughout the module.
3. Local vs Global Variable Conflict
Local variables override global variables within function scope.
4. Using the global Keyword
The global keyword allows modification of global variables inside functions.
5. Enclosing Scope (Nested Functions)
Nested functions can access variables from their enclosing scope.
6. Using the nonlocal Keyword
nonlocal allows modification of variables from the enclosing (but not global) scope.
7. LEGB Rule (Scope Resolution Order)
Python resolves variables using the LEGB rule:
Local
Enclosing
Global
Built-in
8. Built-in Scope
Built-in functions and exceptions reside in the built-in scope.
9. Scope Inside Loops
Unlike some languages, Python loop variables are not block-scoped.
10. Practical Example of Scope Management
Demonstrates coordinated use of local, enclosing, and global scopes.
Last updated