Why does assigning to my global variables not work in Python?

Global variables are special. If you try to assign to a variable a = value inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a global statement inside the function:

a = 7
def setA(value):
    global a   # declare a to be a global
    a = value  # this sets the global value of a

See also Naming and binding for a detailed explanation of Python’s naming and binding rules.

Leave a Comment