Python while 语句上的 Else 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3295938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Else clause on Python while statement
提问by Ivan
I've noticed the following code is legal in Python. My question is why? Is there a specific reason?
我注意到以下代码在 Python 中是合法的。我的问题是为什么?有具体原因吗?
n = 5
while n != 0:
print n
n -= 1
else:
print "what the..."
回答by ars
The elseclause is only executed when your whilecondition becomes false. If you breakout of the loop, or if an exception is raised, it won't be executed.
该else子句仅在您的while条件变为假时执行。如果您break退出循环,或者引发异常,则不会执行。
One way to think about it is as an if/else construct with respect to the condition:
考虑它的一种方法是作为条件的 if/else 构造:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
类似于循环结构:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
一个例子可能是这样的:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
回答by Mark Rushakoff
The else-clause is executed when the while-condition evaluates to false.
else 子句在 while 条件的计算结果为 false 时执行。
From the documentation:
从文档:
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
elseclause, if present, is executed and the loop terminates.A
breakstatement executed in the first suite terminates the loop without executing theelseclause's suite. Acontinuestatement executed in the first suite skips the rest of the suite and goes back to testing the expression.
只要表达式为真,while 语句就用于重复执行:
while_stmt ::= "while" expression ":" suite ["else" ":" suite]这会重复测试表达式,如果为真,则执行第一个套件;如果表达式为假(这可能是第一次测试)
else,则执行子句套件(如果存在)并终止循环。一个
break在首套房执行的语句终止循环,不执行该else条款的套件。continue在第一个套件中执行的语句跳过套件的其余部分并返回测试表达式。
回答by BoltClock
The else:statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0is false).
else:当且仅当 while 循环不再满足其条件时才执行该语句(在您的示例中,whenn != 0为 false)。
So the output would be this:
所以输出将是这样的:
5
4
3
2
1
what the...
回答by John Kugelman
The elseclause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is notexecuted if you breakor returnout of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
else如果您通过命中循环条件或从 try 块的底部正常退出块,则执行该子句。如果您或出块或引发异常,则不会执行它。它不仅适用于 while 和 for 循环,还适用于 try 块。breakreturn
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
您通常会在通常会提前退出循环的地方找到它,而在循环结束时运行是意外/不寻常的情况。例如,如果您在一个列表中循环查找一个值:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
回答by Jean Ferri
The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...
在 Python 中更好地使用 'while: else:' 构造应该是如果在 'while' 中没有执行循环,则执行 'else' 语句。它今天的工作方式没有意义,因为您可以使用下面的代码获得相同的结果......
n = 5
while n != 0:
print n
n -= 1
print "what the..."
回答by Mark
In reply to Is there a specific reason?, here is one interesting application: breaking out of multiple levels of looping.
作为对 的回复Is there a specific reason?,这里有一个有趣的应用程序:打破多级循环。
Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
这是它的工作原理:外循环在最后有一个中断,所以它只会被执行一次。但是,如果内部循环完成(找不到除数),那么它会到达 else 语句并且永远不会到达外部 break。这样,内循环中的中断将中断两个循环,而不仅仅是一个循环。
for k in [2, 3, 5, 7, 11, 13, 17, 25]:
for m in range(2, 10):
if k == m:
continue
print 'trying %s %% %s' % (k, m)
if k % m == 0:
print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
break
else:
continue
print 'breaking another level of loop'
break
else:
print 'no divisor could be found!'
For both whileand forloops, the elsestatement is executed at the end, unless breakwas used.
对于whileandfor循环,else语句在最后执行,除非break被使用。
In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works!
在大多数情况下,有更好的方法来做到这一点(将其包装到函数中或引发异常),但这是有效的!
回答by HVNSweeting
My answer will focus on WHEN we can use while/for-else.
我的回答将集中在我们何时可以使用 while/for-else 上。
At the first glance, it seems there is no different when using
乍一看,使用时似乎没有什么不同
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
and
和
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
Because the print 'ELSE'statement seems always executed in both cases (both when the whileloop finished or not run).
因为该print 'ELSE'语句似乎总是在两种情况下都执行(while循环完成或未运行时)。
Then, it's only different when the statement print 'ELSE'will not be executed.
It's when there is a breakinside the code block under while
那么,只有当语句print 'ELSE'不会被执行时才不同。这是当下面break的代码块中有一个while
In [17]: i = 0
In [18]: while i < 5:
print i
if i == 2:
break
i = i +1
else:
print 'ELSE'
print 'The next statement'
....:
0
1
2
The next statement
If differ to:
如果不同:
In [19]: i = 0
In [20]: while i < 5:
print i
if i == 2:
break
i = i +1
print 'ELSE'
print 'The next statement'
....:
0
1
2
ELSE
The next statement
returnis not in this category, because it does the same effect for two above cases.
return不属于这一类,因为它对上述两种情况具有相同的效果。
exception raise also does not cause difference, because when it raises, where the next code will be executed is in exception handler (except block), the code in elseclause or right after the whileclause will not be executed.
异常引发也不会造成差异,因为当它引发时,下一个代码将在异常处理程序中执行(块除外),else子句中或while子句之后的代码将不会被执行。
回答by Guimoute
It is useful for social interaction.
它对社交互动很有用。
while (Date != "January 1st"):
time.sleep(1)
else:
print("Happy new year!")
回答by Leo Ufimtsev
Else is executed if while loop did not break.
如果 while 循环没有中断,则执行 Else。
I kinda like to think of it with a 'runner' metaphor.
我有点喜欢用“跑步者”的比喻来看待它。
The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only notexecuted if you break somewhere in between.
“其他”就像越过终点线,与您是在赛道的起点还是终点开始无关。如果您在两者之间的某个地方中断,则不会执行“else” 。
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).
主要用例是使用这种打破嵌套循环的方法,或者如果您只想在循环没有在某处中断时才运行某些语句(认为中断是一种不寻常的情况)。
For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:
例如,以下是关于如何在不使用变量或 try/catch 的情况下跳出内部循环的机制:
for i in [1,2,3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 b
# Finished
回答by Iluvatar
I know this is old question but...
我知道这是个老问题,但是......
As Raymond Hettinger said, it should be called while/no_breakinstead of while/else.
I find it easy to understeand if you look at this snippet.
正如 Raymond Hettinger 所说,它应该被称为while/no_break而不是while/else.
如果你看看这个片段,我发现很容易理解。
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
if n == 0:
print n
Now instead of checking condition after while loop we can swap it with elseand get rid of that check.
现在不是在 while 循环之后检查条件,我们可以交换它else并摆脱该检查。
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
I always read it as while/no_breakto understand the code and that syntax makes much more sense to me.
我总是阅读它while/no_break来理解代码,这种语法对我来说更有意义。

