Koushic
Koushic

Reputation: 153

Fibonacci in python - Can some explain how this Fibonacci number between range works?

I am learning python programming and i have run into a bit of jumble. I found this code to compute Fibonacci sequence by user inputted start and end number. Can someone explain how this code works?

def fib(lowerbound, upperbound):
    x = 0
    y = 1
    while x <= upperbound:
        if (x >= lowerbound):
            yield x
        x, y = y, x + y

startNumber = 10
endNumber = 100
for fib_sequence in fib(startNumber, endNumber):
    print "And the next number is... %d!" % fib_sequence

Upvotes: 0

Views: 281

Answers (1)

Sanket Patel
Sanket Patel

Reputation: 386

The function def fib( ... returns a list on which you can iterate using for i in <return val by fib>

I guess your main confusion is around yield part. What it does is it remembers the past values (ie val of x and y) and next time it continues from previous values and whenever it sees yield it adds that yielded value (x here) to the returned list.

https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/

This article shall clear all your doubts.

Cheers!

Upvotes: 1

Related Questions