先看一段程序:
for i in range(10):
if i == 5:
print( 'found it! i = %s' % i)
break
else:
print('not found it ...')
執行結果:
found it! i = 5
必須包含break,如果沒有:
for i in range(10):
if i == 5:
print( 'found it! i = %s' % i)
# break
else:
print('not found it ...')
執行結果:
found it! i = 5 not found it ...
說明:
當迭代的對象迭代完並為空時,位於else的子句將執行,而如果在for循環中含有break時則直接終止循環,並不會執行else子句。
