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

  1. 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 output 1 4 9 16 25 36 49.

  2. Given an integer not less than 2. Print its smallest integer divisor greater than 1. For example input of 15 should output 3.

  3. Given a sequence of non-negative 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 output 17.

  4. Given a sequence of non-negative 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 output 5.6667.

  5. Given a sequence of non-negative integers, where each number is written in a separate line. The sequence ends with 0. Print the maximum value provided in the sequence.

  6. Given a sequence of non-negative 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:

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.