Skip to content

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:

Language: Python
>>> 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:

Language: Python
>>> 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:

Language: Python
>>> 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:

Language: Python
>>> 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
Variables in Python

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.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 28, 2026