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?