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

1
  • 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__() Commented Jun 3, 2020 at 22:33

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

Comments

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)

2 Comments

Thanks. How would I modify this to print just the 10th Fibonacci number?
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)
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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.