首页 > python教程

Python中for后接else的语法使用

时间:2021-07-05 python教程 查看: 687

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")

以上为个人经验,希望能给大家一个参考,也希望大家多多支持python博客。

展开全文
上一篇:python防止栈溢出的实例讲解
下一篇:OpenCV3.3+Python3.6实现图片高斯模糊
输入字:
相关知识
Python 实现图片色彩转换案例

我们在看动漫、影视作品中,当人物在回忆过程中,体现出来的画面一般都是黑白或者褐色的。本文将提供将图片色彩转为黑白或者褐色风格的案例详解,感兴趣的小伙伴可以了解一下。

python初学定义函数

这篇文章主要为大家介绍了python的定义函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助,希望能够给你带来帮助

图文详解Python如何导入自己编写的py文件

有时候自己写了一个py文件,想要把它导入到另一个py文件里面,所以下面这篇文章主要给大家介绍了关于Python如何导入自己编写的py文件的相关资料,需要的朋友可以参考下

python二分法查找实例代码

二分算法是一种效率比较高的查找算法,其输入的是一个有序的元素列表,如果查找元素包含在列表中,二分查找返回其位置,否则返回NONE,下面这篇文章主要给大家介绍了关于python二分法查找的相关资料,需要的朋友可以参考下