嵌套for循环
下列代码是在for中示范else分句以及语句嵌套。这段代码会在对象列表中搜索每个键,然后报告其搜索结果。
>>> items = ["aaa", 111, (4, 5), 2.01]
>>> tests = [(4, 5), 3.14]
>>>
>>> for key in tests:
for item in items:
if item == key:
print(key, 'was found')
break
else:
print (key, 'not found')
>>> tests = [(4, 5), 3.14]
>>>
>>> for key in tests:
for item in items:
if item == key:
print(key, 'was found')
break
else:
print (key, 'not found')
这里的嵌套if会在找到相符结果时,执行break,而循环else分句是认定如果来到此处,搜索就失败了。当这段代码执行时,同时有两个循环在运行:外层循环扫描键列表,而内层循环为每个键扫描列表元素。循环else分句的嵌套是很关键的,其缩进至和内层for循环首行相同的层次,所以是和内层循环相关联的(而不是if或外层for)。
其输出结果是:
((4, 5), 'was found')
(3.14, 'not found')
(3.14, 'not found')
else的错误嵌套之一:
倘若上段代码中的else和if配套的话,代码如下
>>> items = ["aaa", 111, (4, 5), 2.01]
>>> tests = [(4, 5), 3.14]
>>>
>>> for key in tests:
for item in items:
if item == key:
print(key, 'was found')
break
else:
print (key, 'not found')
>>> tests = [(4, 5), 3.14]
>>>
>>> for key in tests:
for item in items:
if item == key:
print(key, 'was found')
break
else:
print (key, 'not found')
其输出结果会是这样子的:
((4, 5), 'not found')
((4, 5), 'not found')
((4, 5), 'was found')
(3.14, 'not found')
(3.14, 'not found')
(3.14, 'not found')
(3.14, 'not found')
((4, 5), 'not found')
((4, 5), 'was found')
(3.14, 'not found')
(3.14, 'not found')
(3.14, 'not found')
(3.14, 'not found')