[Python] Why is global not incrementing in functions (Python)?

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    This code does not work properly:

    def anyFunction(var):
    for i in range(3):
    try:
    exec(var+"+=1")
    except NameError:
    exec("global "+var+"\n"+var+"=1"
    return var

    anyFunction("varInput")
    print(varInput)


    varInput should be 3, but is 1. For the code to work, you need to add a global like this :

    def anyFunction(var):
    for i in range(3):
    try:
    exec("global "+var+"\n"+var+"+=1")
    except NameError:
    exec("global "+var+"\n"+var+"=1"
    return var

    anyFunction("varInput")
    print(varInput)


    Does anyone know if this is a Python bug or is intended ?

    Continue reading...

Compartilhe esta Página