Search code examples
pythonglobal-variablescounter

Global Variable is not Updating


My global variable is not updating, all it prints out is 0. Why is this happening? Are global variables bad practice?

counter = 0
def count():
    global counter
    print(counter)
    counter += 1
    return counter

if __name__ == "__main__":
    count()

Solution

  • You print it first, and only afterwards change its value. If you move

    counter += 1
    

    above the print line, you will see it prints 1.

    It will only print this once, not continuously. Since you are not calling count inside a loop of some kind, it will only update and print the result once.