-1

I am Python amateur and was trying to write a code to generate a Fibonacci Series when I came across a weird behaviour.

>>> def F(num):                    #line1
    a,b = 1,2                      #line2                      
    yield a                        #line3
    yield b                        #line4
    while num>2:                   #line5
        a,b = b,a+b                #line6
        yield b                    #line7


>>> gen = F(10)                    #line8
>>>                                #line9

The while loop in the code is an infinite loop. My question is if the loop does not end then how did #line8 complete execution?

Thanks!!

SohamC
  • 2,367
  • 6
  • 22
  • 34

3 Answers3

1

This is a misconception about yield. Python uses what could be called lazy evaluation. Instead of computing all "yields" in advance, it gets to the first one and stops, and then merely returns an iterator. If you were to call F(10) from the console, you would see an iterator object.

When you start iterating over the list, e.g. by writing [x for x in F(10)], then Python would execute the loop over and over and over again.

If this is confusing, replace yield b with return b. Now the loop is not infinite any more, is it?

Sergey Orshanskiy
  • 6,794
  • 1
  • 46
  • 50
  • The loop will need a decrement operation to be finite...However I understood the cause for line8 to execute!! Thanks for the info!! – SohamC Mar 08 '14 at 06:17
0

The while loop does not end because the variable you are checking never changes inside it. If you were to actually decrement the num variable after each time you yield within the loop, the loop would be finite.

Also, the loop isn't executed once the function is parsed, it is executed after line 8 invokes the function.

Perhaps what is happening would be clearer if you tried actually iterating over the iterable produced by the function:

for i in F(10)
    print i

The result should look like this:

1
2
3
5 
... and so on forever
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
-1

I can't up-vote, but Asad is correct. Just because you define a function doesn't mean it's excited. Assuming you're running this as a script, no code is actually executed until it hits line #8.

aruisdante
  • 8,875
  • 2
  • 30
  • 37