-2

the below code had previously printed the fibonnacci using for loop at end. I moved the print inside the function and then called it but no fibonacci nubers were printed out in spite of the print within the function. Shouldnt they be?

   def fibon(n):
       a = b = 1
       for i in range(n):
           yield a
           a, b = b, a + b
           print(a)  # move here inside function but doesnt print?

   fibon(20)

old code works as:

   for x in fibon(100):
        print(x)  
rupert
  • 9
  • 1
  • 5
  • 4
    You'd still need to iterate over `fibon(20)`, otherwise the function will be "stuck" at the `yield` statement. Perhaps an empty for-loop may work: `for _ in fibon(20): pass`. –  Oct 12 '17 at 07:45
  • 1
    @Reishin: I think you should read more about generators. – anupsabraham Oct 12 '17 at 08:00

3 Answers3

2

The yield statement makes the function returns a generator object, not just a function.

In short, python generators are iterators. PEP 255 that describes simple generators. Generators are used either by calling the next method on the generator object or using the generator object in a for loop.

To execute the generator, you need to iterate over it. So, for x in fibon(20) does the iteration, while fibon(20) returns a generator object.

def fibon(n):
       a = b = 1
       for i in range(n):
           yield a
           a, b = b, a + b
fibon(5)
<generator object fibon at 0x00000000034A6A20>

for i in fibon(5):
    print i

# list() can be used too, because it accepts generator as a param
fibos = list(fibon(5))

If you just change the yield statement to print, you get regular function. But I wouldn't recommend that with fibonacci, the yield option is the way to go.

>>> fibon
<function fibon at 0x0000000002D31C88>
Chen A.
  • 10,140
  • 3
  • 42
  • 61
  • Thanks. One thing I dont get even after reading other links suggested is that if yield replaces return then why does code written after it in the function still run ie in this example the line "a, b = b, a + b" - should the yield stop function? – rupert Oct 12 '17 at 09:44
  • Look at 'what does the yield keyword do' on stackoverflow, hope the explanations there can shed some light on the subject – Chen A. Oct 12 '17 at 10:44
0

In your code fibon is a generator function. And when you call it returns generator object. You could remove yield from function

def fibon(n):
    a = b = 1
    for i in range(n):
        a, b = b, a + b
        print(a)  # move here inside function but doesnt print?

fibon(20)

or construct list from generator object

def fibon(n):
    a = b = 1
    for i in range(n):
        yield a
        a, b = b, a + b
        print(a)  # move here inside function but doesnt print?

list(fibon(20))
CHURLZ
  • 166
  • 10
kvorobiev
  • 5,012
  • 4
  • 29
  • 35
-2

If the goal is only to print the numbers, just replacing yield with print should be enough.

ISV
  • 27
  • 1