我的回答将重点关注在何时可以使用while/for-else。
一开始看起来,使用while/for-else好像没有什么不同之处。
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
and
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
因为无论是否运行while循环(both when the while
loop finished or not run),语句print 'ELSE'
似乎总是被执行。
只有当在while
代码块中存在break
时,才不会执行语句print 'ELSE'
。
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
如果与众不同:
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
return
不在这个范畴中,因为它对两种以上的情况产生相同的效果。
异常抛出也没有差别,因为当它被抛出时,下一行将执行的代码位于异常处理程序(except块)中,else
子句或者while
子句后面的代码都不会被执行。
else
是一个非常糟糕的想法,并且他们不会再做这样的事情了。 - Nicholas Knight