python中for ... else语言陷阱

2017-12-09  本文已影响10人  数字d

从0到9遍历,如果包含5就打印出found it,否则打印 not found it

for i in range(10):
    if i == 5:
        print 'found it! i = %s' % i
else:
    print 'not found it ...'

在以上for的可执行内容为空的时候,默认执行else后的子句

for i in range(10):
    if i == 5:
        print 'found it! i = %s' % i
        break
else:
    print 'not found it ...'

break 跳出整个循环体不再执行 i > 5以后的语句

上一篇 下一篇

猜你喜欢

热点阅读