欢迎来到资源库(www.zyku.net)

Python教程

当前位置:首页 > 网络编程 > Python教程 > 循环

Python中for后接else的语法使用

时间:2022-01-25|栏目:Python教程|点击:|我要投稿

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)

注意:这里的 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循环后执行else

for i in range(5):
     print(i)
else:
    print("打印else")

(资源库 www.zyku.net)

原文链接:https://blog.csdn.net/wj1066/article/details/81913696

上一篇:详解分布式系统中如何用python实现Paxos

栏    目:Python教程

下一篇:Python爬虫之获取心知天气API实时天气数据并弹窗提醒

本文标题:Python中for后接else的语法使用

本文地址:https://www.zyku.net/python/9270.html

关于我们 | 版权申明 | 寻求合作 |

重要申明:本站所有的文章、图片、评论等内容,均由网友发表或上传并维护或收集自网络,仅供个人学习交流使用,版权归原作者所有。

如有侵犯您的版权,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:95148658 | 邮箱:mb8#qq.com(#换成@)

苏ICP备2020066115号-1

本网站由提供CDN加速/云存储服务