Python Variable Scope: Local, Global, and Nonlocal
What Is Variable Scope in Python?
Scope refers to the region of a program where a variable is recognized and can be used. In Python, there are mainly three types of variable scopes:
- Local Scope
- Global Scope
- Nonlocal Scope
1. Local Scope in Python
A variable created inside a function is called a local variable and is only accessible within that function.
Example:
def greet():
message = "Hello from inside!"
print(message)
greet()
# print(message) # This would cause an error (uncomment to test)
Output:
Hello from inside!
2. Global Scope in Python
A global variable is defined outside any function and is accessible throughout the program, even inside functions (read-only by default).
Example:
name = "Alice" # Global variable
def greet():
print("Hello", name)
greet()
Output:
Hello Alice
Modifying Global Variables Inside Functions
To modify a global variable inside a function, use the global keyword.
count = 0
def increment():
global count
count += 1
print("Count inside:", count)
increment()
print("Count outside:", count)
Output:
Count inside: 1 Count outside: 1
3. Nonlocal Scope in Python
The nonlocal keyword is used to modify a variable in the nearest enclosing scope (not global, but not local to the current function either). Commonly used in nested functions.
Example:
def outer():
x = "outer variable"
def inner():
nonlocal x
x = "modified by inner"
print("Inner:", x)
inner()
print("Outer:", x)
outer()
Output:
Inner: modified by inner Outer: modified by inner
Summary Table
Scope Type | Declared In | Accessible In | Modifiable With |
---|---|---|---|
Local | Inside a function | Only that function | N/A |
Global | Outside all functions | Everywhere | global |
Nonlocal | Inside nested functions | Enclosing function's scope | nonlocal |