2
def fib_gen():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(next(fib_gen())) 
print(next(fib_gen())) 
print(next(fib_gen())) 
print(next(fib_gen()))

Output: 0 
        0 
        0 
        0

I am trying to create an infinite Fibonacci generator in python. Please help ... Where am I doing wrong ?

Sameer Pradhan
  • 135
  • 2
  • 15
  • 1
    Possible duplicate of [Python Fibonacci Generator](https://stackoverflow.com/questions/3953749/python-fibonacci-generator) –  Jul 01 '18 at 05:37
  • Thanks but No @insaner.. In infinite series I get this code from web everywhere.. but it is resetting the value of a every-time it is called. – Sameer Pradhan Jul 01 '18 at 05:39

2 Answers2

6

Each call to fib_gen() creates a new generator that is in initial state. Try assigning the return value of fib_gen() to a variable and calling next() on that same variable.

Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
5

You first need to create a generator object:

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


generator = fib_gen()

print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))

The output is:

0
1
1
2