While loops allow your program to repeat a certain piece of code over and over as long as some specific condition is met.
While loops are used as follows:
while (expression): If expression is True, execute this code block . . . Go back to the top of the loop and test expression again When expression is False, continue here...
As an example, imagine you want to write some code to build a countdown timer. The code would start at a specified number of seconds (let's say 60), and then count backwards -- once per second -- until the timer reached zero. At that point, an alarm would go off.
The code for this application is pretty simple:
Create a variable (let's call it time_left
) and set it to 60.
If time_left
has reached 0, jump to Step #5.
Subtract 1 from time_left
and wait a second.
Go back to Step #2
Sound the alarm!
You'll notice that Steps #2-4 will repeat many times (60, to be exact) before our variable gets to 0 and we jump to Step #6. The easiest way to implement that repeating code is to use a while loop, as follows:
In our code above, the first line sets our variable time_left
to 60.
Next, we use a while loop to test whether time_left
equals 0 or not. If the
expression (time_left > 0)
tests true (i.e., we haven't yet gotten to zero), we
subtract 1 from time_left
and go back to the top to test the expression again.
We continue this loop until the expression tests False (i.e., our variable gets to 0), at which point we drop through the loop and start executing the code below it.
The most basic while loop is one that will execute forever. In fact, that's the point of it -- it will keep going until someone explicitly stops the program.
It is written as follows:
Because the expression "True" always evaluates to True, this code block will loop over and over forever until the program is stopped by the user.
One more thing to note -- sometimes we want to break out of a loop while we're in the middle
of executing the code block, even if the expression that we were testing still tests True.
This can be accomplished by using the break
keyword from within the loop, and will
immediately drop through the loop to the code below.