Skip to the content

Project: endless Fibonacci

Python · Unit 15: Comprehensions and generators

The Fibonacci sequence starts at 0 and 1, and each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13…

It never ends, so a generator suits it perfectly: it hands back one value every time it's asked.

a, b = 0, 1
for i in range(5):
    print(a)
    a, b = b, a + b

Prints

0
1
1
2
3

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Fill in the blank so the generator moves on to the next pair of numbers.

  2. 2. Put the lines in order

    Put the lines in order to build the generator and ask it for its first three values.

  3. 3. Write the code

    Write first(n), which returns a list with the first n Fibonacci numbers. fib() is already written: ask it for values with next().

  4. 4. Write the code

    Now below(limit): the list of Fibonacci numbers under limit, in order. Go through fib() with a for and cut it off with break as soon as one reaches the limit.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →