Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.
迭代意味着一次又一次地执行同一段代码。 实现迭代的编程结构称为循环 。
In programming, there are two types of iteration, indefinite and definite:
在编程中,有两种类型的迭代:不确定的和确定的:
With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some condition is met.
With definite iteration, the number of times the designated block will be executed is specified explicitly at the time the loop starts.
Learn about the while loop, the Python control structure used for indefinite iteration
See how to break out of a loop or loop iteration prematurely
Explore infinite loops
了解while循环,这是用于不确定迭代的Python控制结构
了解如何提前退出循环或循环迭代
探索无限循环
When you’re finished, you should have a good grasp of how to use indefinite iteration in Python.
完成后,您应该掌握如何在Python中使用不确定的迭代。
Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.
<statement(s)> represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with indentation, just as in an if statement.
Remember: All control structures in Python use indentation to define blocks. See the discussion on grouping statements in the previous tutorial to review.
切记: Python中的所有控件结构都使用缩进来定义块。 请参阅上一教程中有关分组语句的讨论。
The controlling expression, <expr>, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.
When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop body is executed. Then <expr> is checked again, and if still true, the body is executed again. This continues until <expr> becomes false, at which point program execution proceeds to the first statement beyond the loop body.
>>> n = 5
>>> while n > 0 :
... n -= 1
... print ( n )
...
4
3
2
1
0
Here’s what’s happening in this example:
这是此示例中发生的事情:
n is initially 5. The expression in the while statement header on line 2 is n > 0, which is true, so the loop body executes. Inside the loop body on line 3, n is decremented by 1 to 4, and then printed.
When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression is evaluated again. It is still true, so the body executes again, and 3 is printed.
This continues until n becomes 0. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, but there isn’t one in this case.
Note that the controlling expression of the while loop is tested first, before anything else happens. If it’s false to start with, the loop body will never be executed at all:
>>> n = 0
>>> while n > 0 :
... n -= 1
... print ( n )
...
In the example above, when the loop is encountered, n is 0. The controlling expression n > 0 is already false, so the loop body never executes.
在上面的示例中,遇到循环时, n为0 。 控制表达式n > 0已经为假,因此循环体从不执行。
Here’s another while loop involving a list, rather than a numeric comparison:
这是涉及列表而不是数字比较的另一个while循环:
>>>
>>>
>>> a = [ 'foo' , 'bar' , 'baz' ]
>>> while a :
... print ( a . pop ( - 1 ))
...
baz
bar
foo
When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty. In this example, a is true as long as it has elements in it. Once all the items have been removed with the .pop() method and the list is empty, a is false, and the loop terminates.
In each example you have seen so far, the entire body of the while loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:
break immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.
continue immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.
This time, when n is 2, the continue statement causes termination of that iteration. Thus, 2 isn’t printed. Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. The loop resumes, terminating when n becomes 0, as previously.
Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below:
About now, you may be thinking, “How is that useful?” You could accomplish the same thing by putting those statements immediately after the while loop, without the else:
When <additional_statement(s)> are placed in an else clause, they will be executed only if the loop terminates “by exhaustion”—that is, if the loop iterates until the controlling condition becomes false. If the loop is exited by a break statement, the else clause won’t be executed.
>>> n = 5
>>> while n > 0 :
... n -= 1
... print ( n )
... else :
... print ( 'Loop done.' )
...
4
3
2
1
0
Loop done.
In this case, the loop repeated until the condition was exhausted: n became 0, so n > 0 became false. Because the loop lived out its natural life, so to speak, the else clause was executed. Now observe the difference here:
>>> n = 5
>>> while n > 0 :
... n -= 1
... print ( n )
... if n == 2 :
... break
... else :
... print ( 'Loop done.' )
...
4
3
2
This loop is terminated prematurely with break, so the else clause isn’t executed.
该循环以break提前终止,因此else子句不执行。
It may seem as if the meaning of the word else doesn’t quite fit the while loop as well as it does the if statement. Guido van Rossum, the creator of Python, has actually said that, if he had it to do over again, he’d leave the while loop’s else clause out of the language.
看起来单词else的含义似乎不太适合while循环,也似乎不适合if语句。 实际上,Python的创建者Guido van Rossum曾说过,如果要让它再做一遍,他会把while循环的else子句放在语言之外。
One of the following interpretations might help to make it more intuitive:
以下解释之一可能有助于使其更直观:
Think of the header of the loop (while n > 0) as an if statement (if n > 0) that gets executed over and over, with the else clause finally being executed when the condition becomes false.
Think of else as though it were nobreak, in that the block that follows gets executed if there wasn’t a break.
将循环的标头( while n > 0 )视为一个if语句( if n > 0 ),它会一遍又一遍地执行,当条件变为false时, else子句最终会执行。
想想else好像nobreak ,因为如果没有break ,紧随其后的程序段将被执行。
If you don’t find either of these interpretations helpful, then feel free to ignore them.
如果您对以上两种解释都没有帮助,请随时忽略它们。
When might an else clause on a while loop be useful? One common situation is if you are searching a list for a specific item. You can use break to exit the loop if the item is found, and the else clause can contain code that is meant to be executed if the item isn’t found:
>>> a = [ 'foo' , 'bar' , 'baz' , 'qux' ]
>>> s = 'corge'
>>> i = 0
>>> while i < len ( a ):
... if a [ i ] == s :
... # Processing for item found
... break
... i += 1
... else :
... # Processing for item not found
... print ( s , 'not found in list.' )
...
corge not found in list.
Note: The code shown above is useful to illustrate the concept, but you’d actually be very unlikely to search a list that way.
注意:上面显示的代码对于说明该概念很有用,但是实际上不太可能以这种方式搜索列表。
First of all, lists are usually processed with definite iteration, not a while loop. Definite iteration is covered in the next tutorial in this series.
Secondly, Python provides built-in ways to search for an item in a list. You can use the in operator:
其次,Python提供了内置的方式来搜索列表中的项目。 您可以使用in运算子:
>>>
>>>
>>> if s in a :
... print ( s , 'found in list.' )
... else :
... print ( s , 'not found in list.' )
...
corge not found in list.
The list.index() method would also work. This method raises a ValueError exception if the item isn’t found in the list, so you need to understand exception handling to use it. In Python, you use a try statement to handle an exception. An example is given below:
>>> try :
... print ( a . index ( 'corge' ))
... except ValueError :
... print ( s , 'not found in list.' )
...
corge not found in list.
You will learn about exception handling later in this series.
您将在本系列后面的内容中了解异常处理。
An else clause with a while loop is a bit of an oddity, not often seen. But don’t shy away from it if you find a situation in which you feel it adds clarity to your code!
This code was terminated by Ctrl+C, which generates an interrupt from the keyboard. Otherwise, it would have gone on unendingly. Many foo output lines have been removed and replaced by the vertical ellipsis in the output shown.
Clearly, True will never be false, or we’re all in very big trouble. Thus, while True: initiates an infinite loop that will theoretically run forever.
显然, True永远不会为假,否则我们都将面临巨大麻烦。 因此, while True:启动一个无限循环,理论上它将永远运行。
Maybe that doesn’t sound like something you’d want to do, but this pattern is actually quite common. For example, you might write code for a service that starts up and runs forever accepting service requests. “Forever” in this context means until you shut it down, or until the heat death of the universe, whichever comes first.
More prosaically, remember that loops can be broken out of with the break statement. It may be more straightforward to terminate a loop based on conditions recognized within the loop body, rather than on a condition evaluated at the top.
Here’s another variant of the loop shown above that successively removes items from a list using .pop() until it is empty:
这是上面显示的循环的另一个变体,它使用.pop()连续从列表中删除项目,直到其为空:
>>>
>>>
>>> a = [ 'foo' , 'bar' , 'baz' ]
>>> while True :
... if not a :
... break
... print ( a . pop ( - 1 ))
...
baz
bar
foo
When a becomes empty, not a becomes true, and the break statement exits the loop.
当a变为空时, not a变为true, break语句退出循环。
You can also specify multiple break statements in a loop:
您还可以在循环中指定多个break语句:
In cases like this, where there are multiple reasons to end the loop, it is often cleaner to break out from several different locations, rather than try to specify all the termination conditions in the loop header.
Similarly, a while loop can be contained within another while loop, as shown here:
同样, while循环可以包含在另一个while循环中,如下所示:
>>>
>>>
>>> a = [ 'foo' , 'bar' ]
>>> while len ( a ):
... print ( a . pop ( 0 ))
... b = [ 'baz' , 'qux' ]
... while len ( b ):
... print ( '>' , b . pop ( 0 ))
...
foo
> baz
> qux
bar
> baz
> qux
A break or continue statement found within nested loops applies to the nearest enclosing loop:
在嵌套循环中找到的break或continue语句适用于最近的封闭循环:
Additionally, while loops can be nested inside if/elif/else statements, and vice versa:
In fact, all the Python control structures can be intermingled with one another to whatever extent you need. That is as it should be. Imagine how frustrating it would be if there were unexpected restrictions like “A while loop can’t be contained within an if statement” or “while loops can only be nested inside one another at most four deep.” You’d have a very difficult time remembering them all.
Seemingly arbitrary numeric or logical limitations are considered a sign of poor program language design. Happily, you won’t find many in Python.
似乎任意的数字或逻辑限制被认为是糟糕的程序语言设计的标志。 幸运的是,在Python中找不到很多。
一线while循环(One-Line while Loops)
As with an if statement, a while loop can be specified on one line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;):
This only works with simple statements though. You can’t combine two compound statements into one line. Thus, you can specify a while loop all on one line as above, and you write an if statement on one line: