I l@ve RuBoard |
Python's while statement is its most general iteration construct. In simple terms, it repeatedly executes a block of indented statements, as long as a test at the top keeps evaluating to a true value. When the test becomes false, control continues after all the statements in the while, and the body never runs if the test is false to begin with.
The while statement is one of two looping statements (along with the for, which we'll meet next). We call it a loop, because control keeps looping back to the start of the statement, until the test becomes false. The net effect is that the loop's body is executed repeatedly while the test at the top is true. Python also provides a handful of tools that implicitly loop (iterate), such as the map, reduce, and filter functions, and the in membership test; we explore some of these later in this book.
In its most complex form, the while statement consists of a header line with a test expression, a body of one or more indented statements, and an optional else part that is executed if control exits the loop without running into a break statement (more on these last few words later). Python keeps evaluating the test at the top, and executing the statements nested in the while part, until the test returns a false value:
while <test>: # loop test <statements1> # loop body else: # optional else <statements2> # run if didn't exit loop with break
To illustrate, here are a handful of simple while loops in action. The first just prints a message forever, by nesting a print statement in a while loop. Recall that an integer 1 means true; since the test is always true, Python keeps executing the body forever or until you stop its execution. This sort of behavior is usually called an infinite loop (and tends to be much less welcome when you don't expect it):
>>> while 1: ... print 'Type Ctrl-C to stop me!'
The next example keeps slicing off the first character of a string, until the string is empty. Later in this chapter, we'll see other ways to step more directly through the items in a string.
>>> x = 'spam' >>> while x: ... print x, ... x = x[1:] # strip first character off x ... spam pam am m
Finally, the code below counts from the value of a, up to but not including b. It works much like a C for loop; we'll see an easier way to do this with a Python for and range in a moment.
>>> a=0; b=10 >>> while a < b: # one way to code counter loops ... print a, ... a = a+1 ... 0 1 2 3 4 5 6 7 8 9
Now that we've seen our first Python loop, we should introduce two simple statements that have a purpose only when nested inside loops—the break and continue statements. If you've used C, you can skip most of this section, since they work the same in Python. Since break and loop else clauses are intertwined, we'll say more about else here too. And while we're at it, let's also look at Python's empty statement—the pass, which works just like C's empty statement (a bare semicolon). In Python:
Jumps out of the closest enclosing loop (past the entire loop statement).
Jumps to the top of the closest enclosing loop (to the loop's header line).
Does nothing at all: it's an empty statement placeholder.
Run if and only if the loop is exited normally—i.e., without hitting a break.
When we factor in break and continue statements, the general format of the while loop looks like this:
while <test>: <statements> if <test>: break # exit loop now, skip else if <test>: continue # go to top of loop now else: <statements> # if we didn't hit a 'break'
break and continue statements can appear anywhere inside the while loop's body, but they are usually coded further nested in an if test as we've shown, to take action in response to some sort of condition.
Let's turn to a few simple examples to see how these statements come together in practice. The pass statement is often used to code an empty body for a compound statement. For instance, if you want to code an infinite loop that does nothing each time through, do it with a pass:
while 1: pass # type Ctrl-C to stop me!
Since the body is just an empty statement, Python gets stuck in this loop, silently chewing up CPU cycles.[4] pass is to statements as None is to objects—an explicit nothing. Notice that the while loop's body is on the same line as the header above; as in the if, this only works if the body isn't a compound statement.
[4] This probably isn't the most useful Python program ever written, but frankly, we couldn't think of a better pass example. We'll see other places where it makes sense later in the book (for instance, to define empty classes).
The continue statement sometimes lets you avoid statement nesting; here's an example that uses it to skip odd numbers. It prints all even numbers less than 10 and greater than or equal to 0. Remember, means false, and % is the remainder-of-division operator, so this loop counts down to zero, skipping numbers that aren't multiples of two (it prints 8 6 4 2 0):
x = 10 while x: x = x-1 if x % 2 != 0: continue # odd?--skip print print x,
Because continue jumps to the top of the loop, you don't need to nest the print statement inside an if test; the print is only reached if the continue isn't run. If this sounds similar to a goto in other languages it should; Python has no goto per se, but because continue lets you jump around a program, all the warnings about readability you may have heard about goto apply. It should probably be used sparingly, especially when you're first getting started with Python.
The break statement can often eliminate the search status flags used in other languages. For instance, the following piece of code determines if a number y is prime, by searching for factors greater than one:
x = y / 2 while x > 1: if y % x == 0: # remainder print y, 'has factor', x break # skip else x = x-1 else: # normal exit print y, 'is prime'
Rather than setting a flag to be tested when the loop is exited, insert a break where a factor is found. This way, the loop else can assume that it will be executed only if no factor was found; if you don't hit the break, the number is prime. Notice that a loop else is also run if the body of the loop is never executed, since you don't run a break in that event either; in a while loop, this happens if the test in the header is false to begin with. In the example above, you still get the is prime message if x is initially less than or equal to 1 (e.g., if y is 2).
I l@ve RuBoard |