av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁技術文章
文章詳情頁

Python中for后接else的語法使用

瀏覽:5日期:2022-06-19 13:27:31
0、背景

今天看到了一個比較詭異的寫法,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循環后執行else

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

Python中for后接else的語法使用

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 欧美亚洲国产精品 | 欧美日韩伦理 | 成人毛片网站 | 日韩有码在线观看 | 永久免费av | 亚洲国产区 | 亚洲午夜久久久 | 日本三级大片 | 国产成人97精品免费看片 | 不卡视频一区二区 | 欧美激情一区 | 男女裸体无遮挡做爰 | 成人小视频在线观看 | 欧美不卡视频 | 男人天堂av网 | 天天爽天天爽 | 久久久久久久97 | 久久久久亚洲精品 | 日韩中文字幕一区二区 | 亚洲天堂久久久 | 丁香婷婷网 | 欧美视频精品 | 99精品热 | 国产极品国产极品 | 人人综合 | 在线小视频 | 国产精品一级二级 | 亚洲天堂网在线观看 | 99视频+国产日韩欧美 | 国产剧情在线 | 怡红院在线播放 | 欧美综合一区二区 | 色精品 | 黄色网址在线视频 | 日日干夜夜骑 | 中文字幕第8页 | 欧美深夜福利 | 亚洲一级片在线观看 | 特级西西444www大精品视频 | 免费国产黄色 | 欧美在线视频免费 |