While Loops

for loops are very useful if you know how many iterations of the loop you need. However, there are situations where it's impossible to know in advance how many times you will want the loop body executed. That's what a while loop is used for. while loops are sometimes called conditional loops, since they iterate only as long as some condition is true. Their general form is as follows:

while condition: block

The condition of a while loop is an expression, just like the condition of an if statement. When python encounters a while loop, it evaluates the condition. If that condition is false, Python skips the loop body. If the condition is true, on the other hand, Python executes the loop


Figure 7.4: while loops body once and then goes back to the top of the loop and reevaluates the condition. If it's still true, the loop body is executed again. This is repeated—condition, body, condition, body—until the condition is false, at which point Python stops executing the loop.

Here's a trivial example:

Download loop/simple_while.cmd

>>> rabbits = 3 >>> while rabbits > 0: ... print rabbits ... rabbits -= 1

Notice that this loop did not print 0. When the number of rabbits reaches zero, the loop expression is false, so the body is not executed (see Figure 7.4).

As a more useful example, we can calculate the growth of a bacterial colony using a simple exponential growth model, which is essentially a calculation of compound interest:

In this formula, P(t) is the population size at time t, and r is the growth rate. Let's see how long it takes the bacteria to double their numbers:

Download loop/whileloop.py

population = 1000 # 1000 bacteria to start with growth_rate = 0.21 # 21% growth per minute while population < 2000:

population = population + growth_rate * population print population time = time + 1

print "It took %d minutes for the bacteria to double." % time print "...and the final population was %6.2f bacteria." % population

Because the time variable was updated inside the loop, its value after the loop was the time of the last iteration, which is exactly what we want. Running this program gives us the answer we were looking for:

Download loop/whileloop_output.cmd

1210.0 1464.1 1771.561 2143.58881

It took 4 minutes for the bacteria to double. ...and the final population was 2143.59 bacteria.

Was this article helpful?

0 0

Post a comment