码迷,mamicode.com
首页 > 编程语言 > 详细

Python中for循环搭配else的陷阱

时间:2018-07-21 22:47:17      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:for循环   else   假设   class   写法   range   循环   pytho   对象   

假设有如下代码:

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

你期望的结果是,当找到5时打印出

found it! i = 5

实际上打印出来的结果为:

found it! i = 5
not found it ...

当迭代的对象迭代完并为空时,位于else的子句将执行,而如果在for循环中含有break时则直接终止循环,并不会执行else子句。
所以正确的写法应该为:

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

Python中for循环搭配else的陷阱

标签:for循环   else   假设   class   写法   range   循环   pytho   对象   

原文地址:https://www.cnblogs.com/nyist-xsk/p/9348140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!