Python › Functions & Scope

Why do you need the 'global' keyword to MODIFY a global variable from inside a function, but not to simply READ it?

Intermediate

Answer

Without 'global', assigning to a name inside a function creates a NEW LOCAL variable (shadowing the global one) rather than modifying the global — reading a global variable works fine without any declaration, since Python only needs the 'global' keyword to know your INTENT to assign to (not just read) the outer name.
counter = 0

def increment():
    global counter  # required to MODIFY the global, not just read it
    counter += 1

def read_only():
    print(counter)  # works fine without 'global', since we're only reading

increment()
print(counter)  # 1
Real-world example Modifying a module-level counter or shared state variable from inside a function, correctly signaling intent to the interpreter.

Common follow-ups: How does the 'nonlocal' keyword serve a similar but distinct purpose for ENCLOSING (not global) scope?