Menu Close

How to write the Fibonacci Sequence with Python?

Sometimes, we want to write the Fibonacci Sequence with Python.

In this article, we’ll look at how to write the Fibonacci Sequence with Python.

How to write the Fibonacci Sequence with Python?

To write the Fibonacci Sequence with Python, we can create a generator function.

For instance, we write

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

to create the F generator function.

In it, we assign a and b to their initial values.

And then in a while loop, we yield a and then we assign a and b to the next values in the sequence.

Conclusion

To write the Fibonacci Sequence with Python, we can create a generator function.

Posted in Python, Python Answers