Python for语句后用else可以吗,怎么用
Admin 2022-07-22 群英技术资讯 611 次浏览
今天看到了一个比较诡异的写法,for后直接跟了else语句,起初还以为是没有缩进好,查询后发现果然有这种语法,特此分享。之前写过c++和Java,在for后接else还是第一次见。
# eg1 import numpy as np for i in np.arange(5): print i else: print("hello?") # 0 # 1 # 2 # 3 # 4 # hello?
可以发现,在for正常结束后,break中的语句进行了执行。
# eg2 import numpy as np for i in np.arange(5): print i if (i == 3): break else: print("hello?") # 0 # 1 # 2 # 3
在这个例子当中,i==3的时候break出了循环,然后else当中的语句就没有执行。
总结起来比较简单,如果for循环正常结束,else中语句执行。如果是break的,则不执行。
工程性代码写的比较少,暂时没有想到很好的场景,为了不对其他同学造成干扰,这种形式还是少些一点较好。
官方文档也有解释:
When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause's suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
https://docs.python.org/2/reference/compound_stmts.html#the-for-statement
补充:python里for和else的搭配
for i in range(2,10): for n in range(2,i): if i % n == 0: #print(i, '=', n, '*', i//n) break else: print('found it %s' %i)
注意:这里的 else 并不属于 if 代码块
根据官方文档的解释理解的意思:当迭代的对象迭代完并为空时,位于else的语句将会执行,而如果在for循环里有break时,则会直接终止循环,并不会执行else里的代码
for i in range(10): if i == 7: print('found it %s'%i) break else: print('not found')
可以先运行代码,看一下运行结果,然后将代码块里的break注释掉再运行一遍,与第一次运行的结果进行比较,就会发现不同
补充:python中for―else的用法,执行完for执行else
for i in range(5): print(i) else: print("打印else")
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了Python socket如何实现服务端和客户端数据传输(TCP),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
编写一个程序,要求用户输入24小时制的时间,然后显示12小时制的时间。
Python基础-字符串,元组,数组,字典-公共方法
写爬虫是一个发送请求,提取数据,清洗数据,存储数据的过程。在这个过程中,不同的数据源返回的数据格式各不相同,有 JSON 格式,有 XML 文档,不过大部分还是 HTML 文档,HTML 经常会混杂有转移字符,这些字符我们需要把它转义成真正的字符
本文实例为大家分享了python画条形图的具体代码,供大家参考,具体内容如下在做毕设的过程中有些数据用表格来展现,会很难看出数据之间的差别,凸显不出数据的特点,所以想制作一个条
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008