第308页 | Learning Python | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

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!')

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.

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库