Python中for后接else的语法使用
0、背景
今天看到了一个比较诡异的写法,for后直接跟了else语句,起初还以为是没有缩进好,查询后发现果然有这种语法,特此分享。之前写过c++和Java,在for后接else还是第一次见。
1、试验
# 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当中的语句就没有执行。
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)
可以先运行代码,看一下运行结果,然后将代码块里的break注释掉再运行一遍,与第一次运行的结果进行比较,就会发现不同
补充:python中for—else的用法,执行完for执行else
结束for循环后执行else
for i in range(5): print(i) else: print("打印else")
最后更新于 2021-11-25 09:12:41 并被添加「python else的语法使用 」标签,已有 位童鞋阅读过。
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处
相关文章
- 电子闹钟学生用闹铃强力叫醒桌面智能夜光时钟儿童男女孩起床神器
- html5中canvas学习笔记1-画板的尺寸与实际显示尺寸
- 【新品特惠】官方正版淘气包马小跳漫画升级版全套29册任选加文字版全集任选小学生课外阅读书籍儿童8-10-12岁杨红樱系列书BK
- 一次性眼镜擦拭湿巾擦镜纸眼镜布相机镜头镜片手机清洁纸消毒除菌
- 爱宝熊硅胶安抚奶嘴超软仿母乳新生婴儿带娃睡觉神器0-3到6个月