globalIntermediate Examples

Declares a variable inside a function as belonging to the global scope

When to avoid global

Better alternatives to global variables.

python
# Problem: global state makes code hard to test and debug
counter = 0

def bad_increment():
    global counter
    counter += 1
    return counter

# Better: use a class
class Counter:
    def __init__(self):
        self.value = 0
    def increment(self):
        self.value += 1
        return self.value

c = Counter()
print(c.increment())
print(c.increment())
print(c.increment())

# Or use a closure
def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

inc = make_counter()
print(inc())
print(inc())
Expected Output
1
2
3
1
2

Classes and closures are almost always better than global variables. They allow multiple independent instances and are easier to test.

Global scope rules

Understanding how Python resolves names.

python
x = "global"
y = "global"

def outer():
    y = "outer"

    def inner():
        print(f"x = {x}")  # reads global
        print(f"y = {y}")  # reads outer (enclosing)

    inner()

outer()

# UnboundLocalError: reading before assignment
z = 10
def broken():
    try:
        print(z)  # Error! z is local due to assignment below
    except UnboundLocalError as e:
        print(f"Error: {e}")
    z = 20

broken()
Expected Output
x = global
y = outer
Error: cannot access local variable 'z' before it is assigned

Python determines variable scope at compile time. If a function assigns to a variable, it's local everywhere in that function — even before the assignment.

Want to try these examples interactively?

Open Intermediate Playground