Python中for后接else的语法使用

作者:weijian001 时间:2023-07-08 15:28:47 

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中for后接else的语法使用

来源:https://blog.csdn.net/wj1066/article/details/81913696

标签:Python,for,else
0
投稿

猜你喜欢

  • asp使用模板生成静态页面方法详解

    2007-09-24 12:29:00
  • Tensorflow:转置函数 transpose的使用详解

    2021-01-17 20:36:37
  • 分享Python获取本机IP地址的几种方法

    2022-02-17 12:47:18
  • ajax中get和post的说明及使用与区别

    2024-04-29 13:58:17
  • Python使用pdb调试代码的技巧

    2022-11-18 04:36:06
  • MySql分表、分库、分片和分区知识深入详解

    2024-01-20 19:11:03
  • vue跳转后不记录历史记录的问题

    2023-07-02 17:03:38
  • 用什么视角做产品

    2009-08-18 12:17:00
  • JavaScript实现DOM对象选择器

    2024-05-05 09:15:35
  • 解决SqlServer 各版本 sa帐户不能登录问题

    2024-01-19 11:36:02
  • 使用jupyter Nodebook查看函数或方法的参数以及使用情况

    2022-05-13 08:23:16
  • Python对PDF文件的常用操作方法详解

    2021-10-13 06:49:56
  • 如何让新安装的MySQL数据库变得更安全

    2009-01-04 13:19:00
  • Python叠加两幅栅格图像的实现方法

    2023-07-25 17:14:06
  • 在IE6中用PNG图片实现半透明效果

    2008-05-30 13:14:00
  • python 通过SSHTunnelForwarder隧道连接redis的方法

    2021-03-08 12:58:41
  • SQL Server索引设计基础知识详解使用

    2024-01-19 01:11:31
  • Python基于回溯法子集树模板实现8皇后问题

    2023-09-25 08:34:45
  • 详解PyCharm使用pyQT5进行GUI开发的基本流程

    2021-10-15 22:38:34
  • XHTML与HTML之间的7个区别

    2009-05-20 10:13:00
  • asp之家 网络编程 m.aspxhome.com