What Is a Variable in Python
A variable is a name that references an object in your computer's memory. In Python, variables don't have fixed types — the type belongs to the object the variable points to.
x = 42
x = "now a string"
Local Variables in Python
Defining Local Variables
A local variable is defined inside a function and is only accessible within that function. Once the function finishes executing, the local variable is removed from memory.
def say_hello():
name = "Python" # local variable
print("Hello,", name)
say_hello()
# print(name) # Error: name is not defined
The variable name only exists inside the say_hello function and cannot be accessed outside it.
Benefits of Local Variables
Local variables provide data isolation and prevent accidental changes from other parts of your program. They also automatically free up memory after the function finishes.
Global Variables in Python
What Are Global Variables
A global variable is declared outside all functions and is accessible anywhere in the program file. These variables retain their values throughout the entire program execution.
language = "Python" # global variable
def show():
print("Language:", language)
show() # Language: Python
Problems with Modifying Global Variables
If you try to modify a global variable inside a function without declaring it, you'll get an error:
counter = 0
def increment():
counter += 1 # UnboundLocalError!
Python treats counter as a local variable because of the assignment operation, but it hasn't been defined locally.
The global Keyword
Using global to Modify Global Variables
The global keyword lets you modify global variables from inside a function:
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
Using global in Mathematical Operations
total = 0
def add(x):
global total
total += x
add(10)
add(20)
print(total) # 30
When to Use global
Use the global keyword sparingly — it can make debugging harder and your code less readable.
Variable Scope: The LEGB Rule
How Python Searches for Variables
Python looks up variables using the LEGB rule in this order:
- L (Local) — inside the current function
- E (Enclosing) — in nested functions
- G (Global) — at the module level
- B (Built-in) — Python's built-in names
LEGB Rule Example
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer() # local
Python finds x in the local scope and uses that value.
The nonlocal Keyword
Accessing Variables in Nested Functions
The nonlocal keyword lets you work with variables from an outer (but non-global) scope:
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
f = outer()
print(f()) # 1
print(f()) # 2
Difference Between global and nonlocal
global works with module-level variables, while nonlocal works with variables from enclosing functions within the same scope.