While Loops

Earlier we looked at using for loops to loop through a block of code repeatedly.  Python has another sort of loop called a While loop. 

A while loop is a bit like a repeated if statement.  It says that while a certain condition is true  do something until it is not true.

Here is a piece of code for you to try out:

Follow through each line carefully and try to understand what it does.  Remember to read the last line as counter becomes counter plus one.

Now try the following:

Did you see any difference in the output?  Can you tell why?

Modify the above code so that the counter counts up to 100 in fives. 

Thinking About Loops

All loops need a beginning, middle and end.  When you are setting up your own loops you should think about the following things:

1. Initialising Variables:

2. Inside the Loop: 

3. Ending the Loop:

You can end a loop prematurely by using the break statement