Python中的while循环语句使用'else子句'有什么好处?

4

当while循环中的条件变为False时,while循环后面的任何代码都将执行。在Python的while循环中,“else子句”部分的代码也是如此。那么,在while循环中使用“else”的好处是什么呢?

4个回答

7
如果循环中有一个“break”语句,那么“else”将不会被执行。来自文档的说明:

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 the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

(我加粗的部分)顺便说一下,这也适用于`for`循环。虽然用得不多,但通常在使用时非常优雅。
我相信标准用例是在容器中搜索值。
for element in container:
    if cond(element):
        break
else:
    # no such element

注意,在循环之后,element将在全局范围内被定义,这很方便。
我发现这很难理解,直到我从一些邮件列表中听到了一个很好的解释:

else套件总是在条件已经评估为False时执行。

因此,如果while循环的条件被执行并且被发现为假,则循环将停止并运行else套件。break不同,因为它退出循环而无需测试条件。

1
循环结构的 else 从句是为了消除标志,以区分正常和“异常”循环退出。例如,在 C 语言中,可能会有以下代码:
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标志。


即使在C代码中,found变量也是不必要的,你可以使用if(i!=BUFSIZ)代替if(found) - houbysoft
同意,所以才有了“刻意为之”的部分。 - msw

0
Python循环中的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()

0
引用ars的话:“else子句仅在while条件变为false时执行。如果你跳出循环,或者发生异常,它将不会被执行。”
请参见Python while语句中的else子句

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接