I'm learning Python and ran this piece of code in the python console earlier today:
num = 0
def generator():
while True:
yield num
num += 1
for i in generator():
if i > 5: break
print(i)
It threw a UnboundLocalError: local variable 'num' referenced before assignment
I re-wrote the code and this version worked:
def generator():
num = 0
while True:
yield num
num += 1
for i in generator():
if i > 5: break
print(i)
My question is this: Can you not use local variables inside generator functions like you can with regular functions?
numis not local to your function in the failing codetest()withprint(num)inside it and calltest()in the console, it prints out 0.test()function were to donum += 1you would get the same error (see the question @Mephy linked)yieldfrom your first example, you'll see the same error.