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 ?

2
  • 1
    Possible duplicate of Python Fibonacci Generator Commented Jul 1, 2018 at 5: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. Commented Jul 1, 2018 at 5:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

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.