使用“else 子句”有什么好处? for python 中的 while 循环?

发布于 2024-10-08 20:52:50 字数 112 浏览 2 评论 0原文

while 循环之后的任何代码都会在 while 循环中的条件变为 False 时执行。这与Python中while循环的“else子句”部分的代码相同。那么在 while 循环中使用“else”有什么好处呢?

Any code after while loop will execute when the condition in the while loop becomes False. It is the same for the code in the 'else clause' section of while loop in python. So What's the advantage of having 'else' in the while loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寻梦旅人 2024-10-15 20:52:50

如果循环中有 break 语句,else 将不会执行。来自 文档

while 语句用于
重复执行只要
表达式为真:

while_stmt ::= "while" 表达式 ":" 套件
                [“其他”“:”套件]

这会重复测试表达式
如果为真,则执行第一个
套房;如果表达式为假
(这可能是第一次
已测试)else 子句的套件,
如果存在,则执行并循环
终止。

在中执行的 break 语句
第一个套件终止循环
不执行 else 子句
suite.
执行了 continue 语句
在第一组中跳过其余部分
套件并返回测试
表达。

(强调我的)顺便说一句,这也适用于 for 循环。它并不经常有用,但通常非常优雅。


我相信标准用例是当您在容器中搜索以查找值时:

for element in container:
    if cond(element):
        break
else:
    # no such element

另请注意,在循环之后, element 将在全局范围内定义,这很方便。


我发现它违反直觉,直到我从一些邮件列表中听到一个很好的解释:

else 套件总是在条件评估为 False

时执行

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

else will not execute if there is a break statement in the loop. From the docs:

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.

(emphasis mine) This also works for forloops, by the way. It's not often useful, but usually very elegant when it is.


I believe the standard use case is when you are searching through a container to find a value:

for element in container:
    if cond(element):
        break
else:
    # no such element

Notice also that after the loop, element will be defined in the global scope, which is convenient.


I found it counterintuitive until I heard a good explanation from some mailing list:

else suites always execute when a condition has been evaluated to False

So if the condition of a while loop is executed and found false, the loop will stop and the else suite will run. break is different because it exits the loop without testing the condition.

微暖i 2024-10-15 20:52:50

循环构造的 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
}

而使用循环-else,您可以消除(有点人为的)found 标志

The else clauses for the looping constructs was to eliminate flags to distinguish between normal and "abnormal" loop exits. For example, in C you might have:

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
}

Whereas with a loop-else you can eliminate the (somewhat contrived) found flag

蛮可爱 2024-10-15 20:52:50

引用 ars:“else 子句仅在 while 条件变为 false 时执行。如果跳出循环,或者引发异常,则不会执行该子句。”

请参阅Python while 语句中的 Else 子句

quoting ars: "The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed."

See Else clause on Python while statement .

几味少女 2024-10-15 20:52:50

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()

The else suite on Python loops is best thought of for the case where the loop is performing a search. It's where you handle the case where your search was unsuccessful. (There may be other cases where you might use this, but this is the most common and easily remembered user/case).

The alternative would be to use a sentinel value:

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文