OpenSesame
Rapunzel Code Editor
DataMatrix
Support forum
Python Tutorials
MindProbe
Python videos

Loops: Exercises and Solutions

Fibonacci

Exercise

Calculate the Fibonacci series up to 1,000. Print out each Fibonacci number including its position in the series. Like so:

0: 1
1: 1
2: 2
3: 3
4: 5
etc.

Solution

prev = 1
curr = 1
print('0: {0}'.format(prev))
print('1: {0}'.format(curr))
i = 2
while True:
  prev, curr = curr, prev + curr
  if curr > 1000:
    break
  print('{0}: {1}'.format(i, curr))
  i += 1

Output:

0: 1
1: 1
2: 2
3: 3
4: 5
5: 8
6: 13
7: 21
8: 34
9: 55
10: 89
11: 144
12: 233
13: 377
14: 610
15: 987

You're done with this section!

Continue with loops >>