Python Variables & Scope
In Python, variables are created when you assign a value to them using the assignment operator (=). Python is dynamically typed, meaning you don't need to declare variable types explicitly—Python infers the data type at runtime.
Scope determines where in your code a variable can be accessed or modified. Python uses the LEGB rule to resolve variable names.
1. Python Variables
Variable Declaration & Naming Rules
- Must start with a letter or an underscore (
_). - Cannot start with a number.
- Can only contain alphanumeric characters and underscores (
A-Z,a-z,0-9, and_). - Case-sensitive (
age,Age, andAGEare three different variables). - Cannot be a Python keyword (e.g.,
def,class,import).
x = 10 # int
name = "Alice" # str
is_active = True # bool
# Multiple assignment
a, b, c = 1, 2, "three"
y = z = 0
The LEGB Scope Hierarchy
When you reference a variable, Python searches for it in four sequential scopes (LEGB):
Local --> Enclosing --> global --> Built-in
| Scope | Description |
|---|---|
| Local (L) | Names declared inside a function or lambda expression. |
| Enclosing (E) | Names in the local scope of any and all enclosing/outer functions (closures). |
| Global (G) | Names assigned at the top level of a module/file, or declared using global. |
| Built-in (B) | Pre-assigned names reserved in Python (e.g., print, len, ValueError). |
Scope Examples
Local vs. Global Scope
x = "global x" # Global scope
def my_func():
x = "local x" # Local scope (shadows global x inside this function)
print(x)
my_func() # Output: local x
print(x) # Output: global x
Enclosing Scope (Nested Functions)
def outer():
msg = "enclosing message"
def inner():
# Accesses 'msg' from the enclosing function scope
print(msg)
inner()
outer() # Output: enclosing message
Modifying Scope: global and nonlocal
By default, assigning to a variable inside a function creates a local variable. To modify a global or enclosing variable, you must explicitly declare it.
The global Keyword
Allows a function to modify a variable in the global scope.
counter = 0 # Global variable
def increment():
global counter
counter += 1 # Modifies the global counter
increment()
print(counter) # Output: 1
The nonlocal Keyword
Allows an inner function to modify a variable in its nearest enclosing function scope (excluding global).
def outer():
count = 0 # Enclosing variable
def inner():
nonlocal count
count += 1 # Modifies the enclosing 'count' variable
print(f"Inner count: {count}")
inner()
print(f"Outer count: {count}")
outer()
# Output:
# Inner count: 1
# Outer count: 1
Key Takeaways
- Variables are dynamic references to objects in memory.
- Scope controls visibility and life duration of variables.
- Remember LEGB: Local $\rightarrow$ Enclosing $\rightarrow$ Global $\rightarrow$ Built-in.
- Use
globalto modify top-level variables andnonlocalto modify variables in nested outer functions.