local variable
In Python, a local variable is a name that you assign inside a function or method body, including function parameters.
Local variables live only for the duration of the function execution and are accessible only within that function’s block. Python resolves names using the LEGB rule (Local, Enclosing, Global, Built-ins), so local variables shadow names in outer scopes.
Inside a function, any assignment makes the target name local to the function block unless you use the global or nonlocal keyword.
Example
Basic local variable and visibility:
>>> def greet(name):
... message = f"Hello, {name}!" # Define a local variable, message
... return message
...
>>> greet("Pythonista")
'Hello, Pythonista!'
>>> message
Traceback (most recent call last):
...
NameError: name 'message' is not defined
Assignment makes a name local to a function:
>>> x = 10 # Global x
>>> def assign_global():
... print(x) # Tries to read 'x'
... x = 42 # Makes 'x' local
...
>>> assign_global()
Traceback (most recent call last):
...
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
Use global to rebind a global name:
>>> x = 10
>>> def assign_global():
... global x
... print(x) # Reads the global 'x'
... x = 42 # Rebinds the global 'x'
...
>>> assign_global()
10
>>> x
42
Use nonlocal to rebind names from the enclosing scope:
>>> def make_counter():
... count = 0 # Defines a local name
... def inc():
... nonlocal count # Refers to the enclosing 'count'
... count += 1
... return count
... return inc
...
>>> counter = make_counter()
>>> counter()
1
>>> counter()
2
Related Resources
Tutorial
Python Scope and the LEGB Rule: Resolving Names in Your Code
Understanding Python's variable scope and the LEGB rule helps you avoid name collisions and unexpected behavior. Learn to manage scope and write better code.
For additional information on related topics, take a look at the following resources:
- Namespaces in Python (Tutorial)
- The LEGB Rule & Understanding Python Scope (Course)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces in Python (Quiz)
- Namespaces and Scope in Python (Quiz)
By Leodanis Pozo Ramos • Updated Jan. 9, 2026