Python中for后接else的语法使用
今天看到了一个比较诡异的写法,for后直接跟了else语句,起初还以为是没有缩进好,查询后发现果然有这种语法,特此分享。之前写过c++和Java,在for后接else还是第一次见。
1、试验# eg1import numpy as npfor i in np.arange(5): print ielse: print('hello?')# 0# 1# 2# 3# 4# hello?
可以发现,在for正常结束后,break中的语句进行了执行。
# eg2import numpy as npfor i in np.arange(5): print i if (i == 3):breakelse: print('hello?')# 0# 1# 2# 3
在这个例子当中,i==3的时候break出了循环,然后else当中的语句就没有执行。
2、总结总结起来比较简单,如果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)breakelse: print(’not found’)
可以先运行代码,看一下运行结果,然后将代码块里的break注释掉再运行一遍,与第一次运行的结果进行比较,就会发现不同
补充:python中for—else的用法,执行完for执行else
结束for循环后执行elsefor i in range(5): print(i)else: print('打印else')
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
1. IE6/IE7/IE8/IE9中tbody的innerHTML不能赋值的完美解决方案2. WMLScript的语法基础3. xpath简介_动力节点Java学院整理4. asp中response.write("中文")或者js中文乱码问题5. ASP中格式化时间短日期补0变两位长日期的方法6. jsp实现textarea中的文字保存换行空格存到数据库的方法7. 读大数据量的XML文件的读取问题8. 将properties文件的配置设置为整个Web应用的全局变量实现方法9. 一款功能强大的markdown编辑器tui.editor使用示例详解10. HTML5 Canvas绘制图形从入门到精通
