10.1 while Loops

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 block; 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). It is called 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. Besides statements, Python also provides a handful of tools that implicitly loop (iterate): the map, reduce, and filter functions; the in membership test; list comprehensions; and more. We'll explore most of these in Chapter 14.

10.1.1 General Format

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. 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

10.1.2 Examples

To illustrate, here are a few 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:

>>> 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 and hence false. It's typical to test an object directly like this, instead of using the more verbose equivalent: while x != '':. Later in this chapter, we'll see other ways to step more directly through the items in a string with a for.

>>> x = 'spam' >>> while x: ...     print x, ...     x = x[1:]      # Strip first character off x. ... spam pam am m

The code below counts from the value of a, up to but not including b. We'll see an easier way to do this with a Python for and range later.

>>> a=0; b=10 >>> while a < b:       # One way to code counter loops ...     print a, ...     a += 1         # Or, a = a+1 ... 0 1 2 3 4 5 6 7 8 9


Learning Python
Learning Python: Powerful Object-Oriented Programming
ISBN: 0596158068
EAN: 2147483647
Year: 2003
Pages: 253
Authors: Mark Lutz

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net