Examples

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:

>>> while True:
...    print('Type Ctrl-C to stop me!')

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

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

>>> x = 'spam'
>>> while x:                  # While x is not empty
...     print(x, end=' ')
...     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. The following code 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 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:

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.