Python for语句后用else可以吗,怎么用
Admin 2022-07-22 群英技术资讯 526 次浏览
今天看到了一个比较诡异的写法,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人工智能tensorflow常用激活函数Activation Functions的汇总介绍,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
本文主要给大家介绍的是关于python中scapy模块发包和收包的操作。我们日常上网时,会有很多数据包需要发送,然后处理在接受在发送,如此反复。其中scapy在发包收包起重要作用,下面我们一起来了解一下。
这篇文章主要介绍了Python实现Telnet自动连接检测密码的示例,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
Python的annotate函数用法及应用是什么,有不少朋友对此感兴趣,下面小编给大家整理和分享了相关知识和资料,易于大家学习和理解,有需要的朋友可以借鉴参考,下面我们一起来了解一下吧。
Python内置函数-compile() 函数,compile() 函数将一个字符串编译为字节代码。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008