K
K
kiril4432021-11-18 01:17:32
Python
kiril443, 2021-11-18 01:17:32

Explain why UnboundLocalError: local variable 'error_count' referenced before assignment occurs?

def init_variable():
    global error_count
    error_count = 0

def login():
    error_count += 1   <b> # тут  ошибка</b>

def main():
    init_variable()
    login()

if __name__ == '__main__':
    main()


Explain why an error occurs with the global variable error_count in the line ```` error_count += 1 ````
An error does not occur if you declare in the second function (login) before the global variable ...
If you take out the declaration of global ...; ... = 0 in the main function before calling the login function, an error still occurs.

According to the debug steps, the variable is declared in main.py before the error
61957d9973c2e529155043.png

:

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-11-18
@kiril443

This is how variables work in python.
If a variable is only readable in the local scope (in your case, inside the login() function), then it will be searched sequentially locally, in the scope one level up, and so on up to the global one.
If a variable is written to in a local scope, then it becomes local (and immediately, and not at the time of writing). This behavior is changed by declaring a global or nonlocal variable. I hope I wrote clearly (if anything, there are a lot of materials on the Internet about this, for example )
In your example, error_count in the login () function is local, because. inside the function is writing to it. At the same time, you are trying to read from it before writing (because error_count += 1the essence is error_count = error_count+1).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question