Project: endless Fibonacci
Python · Unit 15: Comprehensions and generators
- Full plan
- Python
- Project
- 4 exercises
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 + bPrints
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. Complete the code
Fill in the blank so the generator moves on to the next pair of numbers.
2. Put the lines in order
Put the lines in order to build the generator and ask it for its first three values.
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 withnext().4. Write the code
Now
below(limit): the list of Fibonacci numbers underlimit, in order. Go throughfib()with aforand cut it off withbreakas soon as one reaches the limit.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.