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 (condition): If condition is True, execute this code block . . . Go back to the top of the loop and test condition again When condition 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 #5. 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.
while
loops are tremendously powerful, and you'll likely be
using them very often. One of the most basic types of while
loops — and also one of the most common — is a loop 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 stop running 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.
Here's an example:
In the code above, we are running in a loop forever, but at one point during each
time through the loop, we're testing for some condition (in this case, we're
testing to see if a SELF DESTRUCT button was pressed!), and if that condition
tests as True
, we drop through the loop.