首页 > 编程语言 > 详细

python 中for与else搭配使用

时间:2019-08-17 12:44:35      阅读:118      评论:0      收藏:0      [点我收藏+]

先看一段程序:

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

python 中for与else搭配使用

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!