Repeating instructiions using “while”

The while loop works very similar to the if statement. The difference being that so long as something is true, it will keep running the same indented section of code. An example:

print("I will count from 1 to 10")
num = 1
while num <= 10:
   print( num )
   num = num + 1
print("The end!")

Exercise: Guessing game

Another new trick is to get the computer to pick a random number for us. The two lines of the code below will pick a random number between 0 and 100.

from random import randint
r = randint(0, 100)

Using this random number generating trick, create a little program where:

Screen shot of the finished product:

Screenshot

Exercise: Fibonacci

The fibonacci sequence is created by summing the two previous numbers together. The first 10 numbers in the sequence are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.

Use a while() loop to create a program that will calculate the n-th number of the sequence. For instance, if asked for the 8th number, it should provide the answer of 21.