该for ... else
语句用于实现搜索循环。
特别是,它处理搜索循环找不到任何东西的情况。
for z in xrange(10):
if z == 5:
# We found what we are looking for
print "we found 5"
break # The else statement will not execute because of the break
else:
# We failed to find what we were looking for
print "we failed to find 5"
z = None
print 'z = ', z
输出:
we found 5
z = 5
该搜索与
z = None
for z in xrange(10):
if 5 == z:
# We found what we are looking for
break
if z == None:
print "we failed to find 5"
else:
print "we found 5"
print 'z = ', z
请记住,如果搜索列表为空(即) ,for
则不会初始化 z 。[]
这就是为什么我们必须确保在搜索后使用 z 时定义它。以下将引发异常,因为z
在我们尝试打印时未定义。
for z in []:
if 5 == z:
break
print "z = ",z
输出
print "z = ",z
NameError: name 'z' is not defined
总之,只要循环自然终止,该else
子句就会执行。如果循环中for
发生中断或异常,则语句将不会执行。for
else