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!")
While exercises

For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order. For example, the input
50
should output1 4 9 16 25 36 49
. 
Given an integer not less than 2. Print its smallest integer divisor greater than 1. For example input of
15
should output3
. 
Given a sequence of nonnegative integers, where each number is written in a separate line. The sequence ends with 0. Print the sum of the sequence. For example the inputs
1
,7
,9
,0
should output17
. 
Given a sequence of nonnegative integers, where each number is written in a separate line. The sequence ends with 0. Print the average of the sequence. For example the inputs
1
,7
,9
,0
should output5.6667
. 
Given a sequence of nonnegative integers, where each number is written in a separate line. The sequence ends with 0. Print the maximum value provided in the sequence.

Given a sequence of nonnegative integers, where each number is written in a separate line. The sequence ends with 0. Print the number of even elements of the sequence.
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:
 The computer picks a random number and stores it as a secret number
 Ask the user to guess the number
 If the guess is higher than the secret number, print the message “too high”
 If the guess is lower than the secret number, print the message “too low”
 If the guess is correct, print the message “you are correct!”
 To use a while loop to keep the game going until the correct guess has been made
 Bonus points: Can you keep count of the number of guesses it takes the player to get it correct?
Screen shot of the finished product:
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 nth number of the sequence. For instance, if asked for the 8th number, it should provide the answer of 21.