A
A
avion2018-03-08 22:32:03
Python
avion, 2018-03-08 22:32:03

Bug in Python?

Hello, when the code is executed everything is fine

length = 100
def len():
    while True:
        if length == 0:
            break
        print(length)

len()

But when it doesn't execute, it throws the error "UnboundLocalError: local variable 'length' referenced before assignment"
length = 100
def len():
    while True:
        length -= 1
        if length == 0:
            break
        print(length)

len()

What is the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Tallmange, 2018-03-08
@avion123678

Python uses a simple rule: if there is an assignment inside the function, then the variable is considered local. That is why the comparison uses a global variable, and in the case of a decrease by one, the interpreter considers the variable as local and does not find its initialization.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question