我同意,这更像是“elif not [condition(s) raise break]”。
我知道这是一个旧线程,但我现在正在研究同一个问题,我不确定是否有人以我理解的方式获得了这个问题的答案。
对我来说,在For... else 或While... else 语句中“阅读”else 有三种方式,它们都是等效的,分别是:
-
else==if the loop completes normally (without a break or error)
-
else==if the loop does not encounter a break
-
else==else not (condition raising break)(想必有这样的条件,不然就不会循环了)
所以,本质上,循环中的“else”实际上是一个“elif ...”,其中“...”是 (1) no break,相当于 (2) NOT [condition( s) 提高休息时间]。
我认为关键是else 没有“中断”就毫无意义,所以for...else 包括:
for:
do stuff
conditional break # implied by else
else not break:
do more stuff
因此,for...else 循环的基本元素如下,您可以用更简单的英语阅读它们:
for:
do stuff
condition:
break
else: # read as "else not break" or "else not condition"
do more stuff
正如其他发帖人所说,当您能够找到循环正在寻找的内容时,通常会引发中断,因此else: 变为“如果找不到目标项目该怎么办”。
示例
您还可以同时使用异常处理、中断和 for 循环。
for x in range(0,3):
print("x: {}".format(x))
if x == 2:
try:
raise AssertionError("ASSERTION ERROR: x is {}".format(x))
except:
print(AssertionError("ASSERTION ERROR: x is {}".format(x)))
break
else:
print("X loop complete without error")
结果
x: 0
x: 1
x: 2
ASSERTION ERROR: x is 2
----------
# loop not completed (hit break), so else didn't run
示例
一个简单的例子,一个中断被击中。
for y in range(0,3):
print("y: {}".format(y))
if y == 2: # will be executed
print("BREAK: y is {}\n----------".format(y))
break
else: # not executed because break is hit
print("y_loop completed without break----------\n")
结果
y: 0
y: 1
y: 2
BREAK: y is 2
----------
# loop not completed (hit break), so else didn't run
示例
没有中断、没有引发中断的条件并且没有遇到错误的简单示例。
for z in range(0,3):
print("z: {}".format(z))
if z == 4: # will not be executed
print("BREAK: z is {}\n".format(y))
break
if z == 4: # will not be executed
raise AssertionError("ASSERTION ERROR: x is {}".format(x))
else:
print("z_loop complete without break or error\n----------\n")
结果
z: 0
z: 1
z: 2
z_loop complete without break or error
----------