While Loops

The second type of loop is a while loop which keeps running until the starting condition has been broken and is no longer true. For example:

while1

While the variable called number is less than 11 this code will print the current number. The last line increases number by 1 otherwise the loop would go on forever as it would never change! For a while loop you must give the variable a value BEFORE the loop or it won’t know what to look for!

while2

 

Inputs inside While Loops

If you want the user to keep entering an input until they give a certain answer then you need to put the input inside the while loop:

while3

I also have put month = ” ” before the loop because Python needs to know the value of the variable before it checks to see if it is not equal to July. We have chosen a default value of just a blank space so that it does not interfere with the program.

That is an important concept. We need to feed Python a default value if we are not going to refer to the variable in the while loop until it is first used inside of the loop (like the month example above). If we are using strings the default value should be a blank space like below:

while5

Or if we are using numbers in a while loop then we need to make our variable equal a default value such as 0 before we use it:

while6

Practice Task 1

While Loops not working? Tick off these common errors:

Correct while loop line?
Have you indented properly?
Have you given the variable a default value?

< Back to Section Six