Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Fibonacci - generator

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


for a in fibonacci():
    print(a)
    if a % 17 == 0:
        print('found')
        break

    if a > 20000:
        print('not found')
        break

Output:

1
1
2
3
5
8
13
21
34
found

When we enter the for loop the fibonacci() function is called and returns a generator object. Then next is called on this generator object which executes the content of the function up to the call of yield and return the value. Then ever time the for-loop calls next the function continues running till it reaches yield again or till it reaches the end of the function. (Which will never happen in this case.)