Conditional Loops

Challenge 3-2: Loops

Conditional loops repeat until something happens (or as long as some condition is True).

>>> mycount = 0

>>> while (mycount < 4):

print('The count is:', mycount)

mycount = mycount + 1


The count is: 0

The count is: 1

The count is: 2

The count is: 3

Notice that before we start our loop, we create a variable named mycount and give it a value of zero.

>>> mycount = 0

The first thing this loop does is ask if the current value of mycount is less than 4. Well, we just gave it a value of 0, so we know that is True.

>>> while (mycount < 4):

This expression is True, so Python can run the code in the indented lines below it. Python prints the words 'The count is:' along with the value of mycount, which is 0.

print('The count is:', mycount)

But what is that expression below the print statement? Remember that we can use variables in some math operations. Since the current value of mycount is 0, we can add 1 to it, and the value of mycount becomes 1.

mycount = mycount + 1

Back up at the top of the loop, in the while statement, Python asks once again if the value of mycount is less than 4. Well, the value of mycount has changed - it's now 1. But that is still less than 4, so we can continue. Python prints 'The count is: 1' and then adds 1 to the value of mycount.

Now the value of mycount has been increased to 2. Is that less than 4? Why, yes it is. So Python prints 'The count is: 2' and then adds 1 to mycount.

The value of mycount is now 3, and that is still less than 4, so again Python prints, and again adds 1 to the mycount.

But wait - is mycount still less than 4? Nope - mycount is now equal to 4. So that while statement is no longer True, and the loop stops running.

The while keyword is used to create this kind of loop, so it is usually just called a while loop.