使用“else 子句”有什么好处? for python 中的 while 循环?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果循环中有
break
语句,else
将不会执行。来自 文档:(强调我的)顺便说一句,这也适用于 for 循环。它并不经常有用,但通常非常优雅。
我相信标准用例是当您在容器中搜索以查找值时:
另请注意,在循环之后,
element
将在全局范围内定义,这很方便。我发现它违反直觉,直到我从一些邮件列表中听到一个很好的解释:
因此,如果执行
while
循环的条件并发现 false,循环将停止并且else
套件将运行。break
是不同的,因为它退出循环而不测试条件。else
will not execute if there is abreak
statement in the loop. From the docs:(emphasis mine) This also works for
for
loops, 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:
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:
So if the condition of a
while
loop is executed and found false, the loop will stop and theelse
suite will run.break
is different because it exits the loop without testing the condition.循环构造的 else 子句是消除用于区分正常和“异常”循环退出的标志。例如,在 C 中,您可能有:
而使用循环-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:
Whereas with a loop-else you can eliminate the (somewhat contrived)
found
flag引用 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 .
Python 循环上的
else
套件最适合循环执行搜索的情况。这是您处理搜索不成功的情况的地方。 (可能在其他情况下您可能会使用它,但这是最常见且容易记住的用户/案例)。另一种方法是使用哨兵值:
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: