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
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))
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))
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 (ie 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.