1
def fibonacci_sequence():
    a,b = 1,1
    while True:
        yield a
        a,b = b, a+b

for i in range(10):
    print(fibonacci_sequence().__next__())

I tried using this in Python 3 to print out the fibonacci series. But the program just ends up printing 1 over and over again

Bharath PS
  • 11
  • 1
  • 2
  • Because you keep creating a new generator object, `fibonnacci_sequence()` and then you call `__next__()` on that new object, so of course, you only ever get the first value. As an aside, the **whole point** of generators is that you can iterate directly over them (they are iterators). Note also, you shouldn't call dunder methods directly, so if you *do* need it, use `next(some_iterator)` not `some_iterator.__next__()` – juanpa.arrivillaga Jun 03 '20 at 22:33

3 Answers3

2

You are declaring on each iteration a new generator you need to create one outside of the loop.

def fibonacci_sequence():
    a,b = 1,1
    while True:
        yield a
        a,b = b, a+b

generator = fibonacci_sequence()
for i in range(10):
    print(generator.__next__())

You could also use next()

generator = fibonacci_sequence()
for i in range(10):
    print(next(generator))
Bernardo Duarte
  • 4,074
  • 4
  • 19
  • 34
0

You are re-initializing the fibonacci_sequence each time in loop, do it like this:

def fibonacci_sequence():
    a,b = 1,1
    while True:
        yield a
        a,b = b, a+b

f = fibonacci_sequence()

for i in range(10):
    print(next(f))
alani
  • 12,573
  • 2
  • 13
  • 23
zipa
  • 27,316
  • 6
  • 40
  • 58
0

As said already, you need to instantiate the generator once only, outside the loop.

Also, avoid calling __next__ directly, use next(generator/iterator) instead.

Having said that, in this simple case just let the for instruction handle the iteration protocol (i.e. call iter, call next and catch the StopIteration exception).

We can also write the loop as:

import itertools as it

def fibonacci_sequence():
    a,b = 1,1
    while True:
        yield a
        a,b = b, a+b

for k in it.islice(fibonacci_sequence(),10):
    print(k)
Pynchia
  • 10,996
  • 5
  • 34
  • 43
  • Thanks. How would I modify this to print just the 10th Fibonacci number? – Bharath PS Jun 03 '20 at 23:31
  • [islice](https://docs.python.org/3/library/itertools.html#itertools.islice) allows to define the slice in several ways, exactly like you would with indexes. For example we can pass it where to start and end: `it.islice(fibonacci_sequence(),9,10)` – Pynchia Jun 04 '20 at 05:39