Python’s while statement is the most general iteration construct in the language. In simple terms, it repeatedly executes a block of (normally indented) statements as long as a test at the top keeps evaluating to a true value. It is called a “loop” because control keeps looping back to the start of the statement until the test becomes false. When the test becomes false, control passes to the statement that follows the while block. The net effect is that the loop’s body is executed repeatedly while the test at the top is true. If the test is false to begin with, the body never runs and the while statement is skipped.
In its most complex form, the while statement consists of a header line with a test expression, a body of one or more normally indented statements, and an optional else part that is executed if control exits the loop without a break statement being encountered. Python keeps evaluating the test at the top and executing the statements nested in the loop body until the test returns a false value:
whiletest: # Loop teststatements# Loop body else: # Optional elsestatements# Run if didn't exit loop with break
To illustrate, let’s look at a few simple while loops in action. The first, which consists of a print statement nested in a while loop, just prints a message forever. Recall that True is just a custom version of the integer 1 and always stands for a Boolean true value; because 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—it’s not really immortal, but you may need a Ctrl-C key combination to forcibly terminate one:
>>>while True:...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 through the items in a string more easily with a for loop.
>>>x = 'spam'>>>while x:# While x is not empty ...print(x, end=' ')# In 2.X use print x, ...x = x[1:]# Strip first character off x ... spam pam am m
Note the end=' ' keyword argument used here to place all outputs on the same line separated by a space; see Chapter 11 if you’ve forgotten why this works as it does. This may leave your input prompt in an odd state at the end of your output; type Enter to reset. Python 2.X readers: also remember to use a trailing comma instead of end in the prints like this.
The following code counts from the value of a up to, but not including, b. We’ll also see an easier way to do this with a Python for loop and the built-in range function later:
>>>a=0; b=10>>>while a < b:# One way to code counter loops ...print(a, end=' ')...a += 1# Or, a = a + 1 ... 0 1 2 3 4 5 6 7 8 9
Finally, notice that Python doesn’t have what some languages call a “do until” loop statement. However, we can simulate one with a test and break at the bottom of the loop body, so that the loop’s body is always run at least once:
while True:
...loop body...
if exitTest(): break
To fully understand how this structure works, we need to move on to the next section and learn more about the break statement.