[Python] Why do I get a 'referenced before assignment' error, for a variable that has been...

Discussão em 'Python' iniciado por Stack, Março 31, 2025.

  1. Stack

    Stack Membro Participativo

    This code:

    my_num = 0

    def my_func():
    my_num = my_num + 1
    my_func()


    causes the following error:


    Traceback (most recent call last): File "main.py", line 5, in my_func() File "main.py", line 4, in my_func my_num = my_num + 1 UnboundLocalError: local variable 'my_num' referenced before assignment
    ​

    Why does the interpreter not read the expression as:

    my_num = 0 + 1

    Continue reading...

Compartilhe esta Página