当while循环中的条件变为False时,while循环后面的任何代码都将执行。在Python的while循环中,“else子句”部分的代码也是如此。那么,在while循环中使用“else”的好处是什么呢?
(我加粗的部分)顺便说一下,这也适用于`for`循环。虽然用得不多,但通常在使用时非常优雅。The
while
statement is used for repeated execution as long as an expression is true:while_stmt ::= "while" expression ":" suite ["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the
else
clause, if present, is executed and the loop terminates.A
break
statement executed in the first suite terminates the loop without executing theelse
clause’s suite. Acontinue
statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
for element in container:
if cond(element):
break
else:
# no such element
element
将在全局范围内被定义,这很方便。
因此,如果
else
套件总是在条件已经评估为False
时执行。
while
循环的条件被执行并且被发现为假,则循环将停止并运行else
套件。break
不同,因为它退出循环而无需测试条件。int found = 0;
for(int i = 0; i < BUFSIZ; i++) {
if(...predicate..) {
found++;
break;
}
}
if(found) {
// I broke out of the for
} else {
// the for loop hit BUFSIZ
}
如果使用循环-否则语句,您可以消除(有些人为的)found
标志。
else
套件最好用于执行搜索的情况。这是处理搜索失败的情况的地方。(可能还有其他情况可以使用,但这是最常见和容易记住的用户/案例)。sentinel = object()
result = sentinel
for each_item in some_container:
if matches_some_criteria(each_item):
result = each_item
break
if result is sentinel:
do_something_about_failure()
found
变量也是不必要的,你可以使用if(i!=BUFSIZ)
代替if(found)
。 - houbysoft