美文网首页
python中for ... else语言陷阱

python中for ... else语言陷阱

作者: 数字d | 来源:发表于2017-12-09 14:23 被阅读10次

从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以后的语句

相关文章

网友评论

      本文标题:python中for ... else语言陷阱

      本文链接:https://www.haomeiwen.com/subject/xsjkixtx.html