-1

What is the behavior of local variables in while loops? I would have imagined the value of a would be taken from the global variable external to the function. Is there some kind of rule which excludes global variables from within the conditional expression of a while statement? It seems to detect that a is not defined within the function. If i change the while loop to an if statement using the same variable a, there is no local unbound error

Ofcourse i could jsut move the assignment of a into the function, but im interested in the behaviour of local variables in while loop expressions

FiboList = []
a, b = 0, 1
def i_fibonacci(n):
    while a < n:
        FiboList.append(a)
        a, b = b, a+b



File "c:\Users\Dell\Desktop\PythonPlayground\fibonacci.py", line 30, in i_fibonacci
        while a < n:
    UnboundLocalError: local variable 'a' referenced before assignment

0 Answers0