Advertisement
❮ Previous: Python Output & Input Next: Python Data Types ❯

Python Variables & Scope

In Python, variables are created when you assign a value to them using the assignment operator (=). Python is dynamically typed, meaning you don't need to declare variable types explicitly—Python infers the data type at runtime.

Scope determines where in your code a variable can be accessed or modified. Python uses the LEGB rule to resolve variable names.


1. Python Variables

Variable Declaration & Naming Rules

x = 10                  # int
name = "Alice"          # str
is_active = True        # bool

# Multiple assignment
a, b, c = 1, 2, "three"
y = z = 0

Try this code ❯


Advertisement

The LEGB Scope Hierarchy

When you reference a variable, Python searches for it in four sequential scopes (LEGB):


Local --> Enclosing --> global --> Built-in

Scope Description
Local (L) Names declared inside a function or lambda expression.
Enclosing (E) Names in the local scope of any and all enclosing/outer functions (closures).
Global (G) Names assigned at the top level of a module/file, or declared using global.
Built-in (B) Pre-assigned names reserved in Python (e.g., print, len, ValueError).

Advertisement

Scope Examples

Local vs. Global Scope

x = "global x"  # Global scope

def my_func():
    x = "local x"  # Local scope (shadows global x inside this function)
    print(x)

my_func()  # Output: local x
print(x)   # Output: global x

Try this code ❯

Enclosing Scope (Nested Functions)

def outer():
    msg = "enclosing message"
    
    def inner():
        # Accesses 'msg' from the enclosing function scope
        print(msg)
        
    inner()

outer()  # Output: enclosing message

Try this code ❯


Advertisement

Modifying Scope: global and nonlocal

By default, assigning to a variable inside a function creates a local variable. To modify a global or enclosing variable, you must explicitly declare it.

The global Keyword

Allows a function to modify a variable in the global scope.

counter = 0  # Global variable

def increment():
    global counter
    counter += 1  # Modifies the global counter

increment()
print(counter)  # Output: 1

Try this code ❯

The nonlocal Keyword

Allows an inner function to modify a variable in its nearest enclosing function scope (excluding global).

def outer():
    count = 0  # Enclosing variable
    
    def inner():
        nonlocal count
        count += 1  # Modifies the enclosing 'count' variable
        print(f"Inner count: {count}")
        
    inner()
    print(f"Outer count: {count}")

outer()
# Output:
# Inner count: 1
# Outer count: 1

Try this code ❯


Advertisement

Key Takeaways

❮ Previous: Python Output & Input Next: Python Data Types ❯
Advertisement