Answer the question
In order to leave comments, you need to log in
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()
Answer the question
In order to leave comments, you need to log in
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 += 1
the essence is error_count = error_count+1
).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question