为什么“else"的目的是“for"后面的子句或“同时"环形? [英] Why is the purpose of the "else" clause following a "for" or "while" loop?
问题描述
我是 Python 初学者.我发现 for
-else
和 while
-else
中的 else
完全是不必要.因为for
和while
最终会运行到else
,我们可以使用通常的行来代替.
I am a Python beginner. I find that the else
in for
-else
and while
-else
is completely unnecessary. Because for
and while
will finally run to else
, and we can use the usual lines instead.
例如:
for i in range(1, 5):
print i
else:
print 'over'
和
for i in range(1, 5):
print i
print 'over'
都一样.
那么为什么Python在for
-else
和while
-else
中有else
代码>?
So why does Python have else
in for
-else
and while
-else
?
推荐答案
你对 for/else 的语义理解有误.else 子句仅在循环完成时运行,例如,如果没有遇到 break 语句.
You are wrong about the semantics of for/else. The else clause runs only if the loop completed, for example, if a break statement wasn't encountered.
典型的 for/else 循环如下所示:
The typical for/else loop looks like this:
for x in seq:
if cond(x):
break
else:
print "Didn't find an x I liked!"
将else"视为与循环体中的所有if"配对.您的示例是相同的,但混合了break"语句,它们不是.
Think of the "else" as pairing with all of the "if's" in the loop body. Your samples are the same, but with "break" statements in the mix, they are not.
对同一想法的更长描述:http://nedbatchelder.com/blog/201110/forelse.html
A longer description of the same idea: http://nedbatchelder.com/blog/201110/forelse.html
这篇关于为什么“else"的目的是“for"后面的子句或“同时"环形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!