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?
IntermediateAnswer
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) # 1Real-world example Modifying a module-level counter or shared state variable from inside a function, correctly signaling intent to the interpreter.