Understanding Python Global, Local, and Nonlocal Variables
Understanding Python Global, Local, and Nonlocal Variables
Master the use of global, local, and nonlocal variables in Python, and know when to apply each for clean, maintainable code.
Video: Python Local and Global Variables
Global Variables
In Python, a variable declared outside any function—at module level—is a global variable. It can be read from anywhere in the module, but must be declared with the global keyword if you want to modify it inside a function.
Example: creating and reading a global variable
x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
Output
x inside: global x outside: global
Attempting to reassign x without declaring it global results in an UnboundLocalError:
x = "global"
def foo():
x = x * 2
print(x)
foo()
Output
UnboundLocalError: local variable 'x' referenced before assignment
To modify a global variable inside a function, use the global keyword:
x = "global"
def foo():
global x
x = x * 2
print(x)
foo()
Output
globalglobal
Local Variables
A local variable is defined within a function’s body and exists only during that function’s execution. It cannot be accessed outside the function.
Example: accessing a local variable outside its scope
def foo():
y = "local"
foo()
print(y)
Output
NameError: name 'y' is not defined
Defining and using a local variable correctly:
def foo():
y = "local"
print(y)
foo()
Output
local
Combining Global and Local Variables
It’s common to use both scopes in the same module. The global keyword ensures that a variable refers to the module-level instance.
x = "global "
def foo():
global x
y = "local"
x = x * 2
print(x)
print(y)
foo()
Output
global global local
When a local variable shares a name with a global one, they are independent:
x = 5
def foo():
x = 10
print("local x:", x)
foo()
print("global x:", x)
Output
local x: 10 global x: 5
Nonlocal Variables
Nested functions can access and modify variables from their enclosing (but not global) scope using the nonlocal keyword.
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
Output
inner: nonlocal outer: nonlocal
Note: Updating a nonlocal variable inside the inner function updates the variable in the outer function’s scope.
Python
- Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
- Python Statements, Indentation, and Comments: A Clear Guide
- Python Variables, Constants, and Literals – A Comprehensive Guide
- Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
- Mastering Python Loop Control: break & continue
- Mastering Python’s Global Keyword: How and When to Use It
- Mastering Directory and File Operations in Python
- Python vs JavaScript: Key Differences, Features, and When to Choose Each
- Python vs Ruby: A Comprehensive Comparison of Features, Advantages, and Use Cases
- Python Variable Types: Understanding and Using Data Types