/* jquery */ /* jquery accordion style*/ /* jquery init */

31 March 2013

Learn Python - While Loops

One very common loop style is created with a 'while' statement. This kind of loop doesn't have a fixed number of iterations, but will repeat until a certain condition is met. Let's look at a simple example to see how it works in practice.

Suppose we want to count down from ten to one. Here's an example the loop code we'll need:

x = 10
while x > 0:
  print x
  x = x - 1
print "finished"

There are a number of interesting points here, so I'll go through them one by one. First we assign the variable 'x' a value of ten. Next we have our loop statement, complete with condition. A condition is simply a test to determine if something will evaluate to 'True' or 'False'. In this case we test the value of 'x' to see if it's greater than zero.

Notice the colon ':' at the end of the line. This character marks the start of our loop code. You'll also see the next two lines have been indented by adding some spaces before the statement. In Python every line that is indented after a loop colon will be executed every time the loop repeats.

(Note these indented lines have the same level of indentation - if they don't a Python error will be generated when the program runs.)

The last line isn't indented, which means it isn't part of the of the loop, and so will only be executed after the last loop cycle.

So, what does the code do?

Well, the first time the loop executes the value of 'x' is ten. As ten is greater than zero the conditional test 'x > 0' is 'True'. So, it will print out the value of 'x', then decrement it by one. The next time the loop repeats the value of 'x' will be nine. As nine is also greater than zero the loop will again print the value of 'x' and decrement it by one. Looping continues until 'x' is zero.

When 'x' is zero the test 'x > 0' will be 'False', and the loop exits. This means the program will continue from the first line after the loop. In this case that's the final print statement.

A post from my Learn Python on the Raspberry Pi tutorial.