What is the use of “else” after “for” loop in Python?
本问题已经有最佳答案,请猛点这里访问。
下面的两个代码似乎都在打印相同的代码,那么在python中"for"循环之后需要"else"块。
代码1:
1 2 3 4 | for i in range(10): print i else: print"after for loop" |
代码2:
1 2 3 4 | for i in range(10): print i print"after for loop" |
事先谢谢。
1 2 3 4 5 6 7 | for i in range(10): print i if (i == 8): break # termination, no else else: print"after for loop" |
从文档中:
Loop statements may have an
else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
下面的链接是一个如何使用它的示例。
这最初是为了在不使用标志的情况下除去过程中的所有"goto"语句而制定的:意思是"不休息"
1 2 3 4 5 6 | for i, value in enumerate(sequence): if value == target: break else: #<-- if we finish the loop and did not encounter break, return -1 return -1 return 1 #<-- if we did encounter break, return 1 |
你可以观看Raymond Hettinger的pycon talk,其中提到for/else结构:将代码转换为漂亮的惯用python,http://pyvideo.org/video/1780/transforming-code-into-beautiful-iduatic-pytho