I am currently studying Python and have become a bit stuck on the Fibonacci Number Generator. After a few hours of research I haven't made much progress. I understand the output to a certain extent, I just don't feel comfortable moving to another topic until I know what is happening here for every iteration.
def fibonacci_generator() :
a , b = 0 , 1
while True :
yield a
a , b = b , a + b
fib = fibonacci_generator()
for i in fib :
if i > 100 :
break
else :
print( 'Generated:' , i )
After running this code, I see the following output.
Generated: 0
Generated: 1
Generated: 1
Generated: 2
Generated: 3
Generated: 5
Generated: 8
Generated: 13
Generated: 21
Generated: 34
Generated: 55
Generated: 89
According to several answers to similar questions here on Stack Overflow, I do understand that the first time the generator is called, a and be are initialized to 0 and 1 respectively, and then the value with the yield statement ( a = 0) is returned back to the caller.
To save a little time and make things perfectly clear, there are a few questions have.
In the first iteration, is the only occurrence the return of the initial value of a? Does it completely stop at yield?
In the second iteration, where does it get 1? If a, b = b, then a + b would be 1+1, so why isn't the second value returned as 2?
I'm also not sure how the same value of 1 gets returned twice.
To sum it all up, I would like to know what the specific operation is for every line of the output. I can't seem to get that part straight in my head. Let me reiterate that I have looked in quite a few different places but nothing I've seen has helped.