当前位置:首页 > Python教程 > python技巧

python 中for与else搭配使用

先看一段程序:

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子句。

原文:https://www.cnblogs.com/ivyharding/p/11367925.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐