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
Variables in Python: Usage and Best Practices
Explore Python variables from creation to best practices, covering naming conventions, dynamic typing, variable scope, and type hints with examples.
For additional information on related topics, take a look at the following resources:
- Python Scope and the LEGB Rule: Resolving Names in Your Code (Tutorial)
- Using and Creating Global Variables in Your Python Functions (Tutorial)
- Python Closures: Common Use Cases and Examples (Tutorial)
- Defining Your Own Python Function (Tutorial)
- Namespaces in Python (Tutorial)
- The LEGB Rule & Understanding Python Scope (Course)
- Variables in Python (Course)
- Variables in Python: Usage and Best Practices (Quiz)
- Working With Global Variables in Python Functions (Course)
- Using and Creating Global Variables in Your Python Functions (Quiz)
- Exploring Python Closures: Examples and Use Cases (Course)
- Python Closures: Common Use Cases and Examples (Quiz)
- Defining and Calling Python Functions (Course)
- Defining Your Own Python Function (Quiz)
- Defining and Calling Python Functions (Quiz)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces in Python (Quiz)
- Namespaces and Scope in Python (Quiz)
By Leodanis Pozo Ramos • Updated July 28, 2026