Categories
Python Answers

How to write the Fibonacci Sequence with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *