2-3 Conditional Loops

We have covered the sequence and decision control structures so far.  There is one more important control structure we need to discuss: the repetition structure.  A repetition structure (commonly called a loop) causes the Python interpreter to repeat a statement or set of statements more than once.  Another word for “repeat” is “iterate”, so each time the body of a loop is repeated it’s called an iteration of the loop.  Later we’ll see that almost every line of code you write in a game is inside some kind of loop that will repeat many times per second.

There are two categories of loops: condition-controlled and counter-controlled.  Today we’ll discuss condition-controlled loops, and next time counter-controlled loops.

The while Loop

A conditional loop causes a statement or set of statements to repeat as long as a condition is True.  Another way of thinking about this is like an if statement that repeats over and over as long as its condition remains True.  In Python, we use the while statement to write a conditional loop: Like an if statement, the while statement begins with a Boolean expression that will result in either True or False.  If the result of the condition is True, then the body of the loop executes once.  The condition is then checked again, and the process repeats until the condition yields a Falseresult causing the loop to stop.

Here is an example that counts from 1 to 10:

Because the condition is checked before the loop body runs, the while loop is known as a pre-test loop.  As shown, you must ensure that any variable(s) used in the condition (in this case number) have been defined outside the loop with a starting value that will cause the condition to be True at least the first time.  If the condition is not True when the while loop starts, then the body will not be repeated even one time – the loop will do nothing.

Similarly, it’s important to ensure that at some iteration of the loop the condition will yield a False result.  If this never happens, then the body of the loop will be repeated over and over, infinitely!  A loop that never stops iterating is called an infinite loop and is usually the result of a logic error in the condition.  For example, consider the following code:

Can you spot the logic error?  Because health starts with a value of 10, and 3 is subtracted each time the body of the loop repeats, health will never be assigned a value of 0.  That is, it will be decreased like this: 10, 7, 4, 1, -2, -5, -7, -11 and so on forever!  There are different ways to fix this bug, but the easiest would be to revise the condition to:

This ensures that the while loop stops when health is <= 0.

You Try!

    1. Start a new page in your Learning Journal titled “2-3 Conditional Loops“.  Carefully read the notes above and in your own words summarize the key ideas from each section.
    2. How many times will “Hello World” print in the following program, explain why.  Fix the code!