午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

您的位置:首頁技術(shù)文章
文章詳情頁

Python中for后接else的語法使用

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

今天看到了一個比較詭異的寫法,for后直接跟了else語句,起初還以為是沒有縮進(jìn)好,查詢后發(fā)現(xiàn)果然有這種語法,特此分享。之前寫過c++和Java,在for后接else還是第一次見。

1、試驗

# eg1import numpy as npfor i in np.arange(5): print ielse: print('hello?')# 0# 1# 2# 3# 4# hello?

可以發(fā)現(xiàn),在for正常結(jié)束后,break中的語句進(jìn)行了執(zhí)行。

# eg2import numpy as npfor i in np.arange(5): print i if (i == 3):breakelse: print('hello?')# 0# 1# 2# 3

在這個例子當(dāng)中,i==3的時候break出了循環(huán),然后else當(dāng)中的語句就沒有執(zhí)行。

2、總結(jié)

總結(jié)起來比較簡單,如果for循環(huán)正常結(jié)束,else中語句執(zhí)行。如果是break的,則不執(zhí)行。

工程性代碼寫的比較少,暫時沒有想到很好的場景,為了不對其他同學(xué)造成干擾,這種形式還是少些一點較好。

官方文檔也有解釋:

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

補(bǔ)充:python里for和else的搭配

用找質(zhì)數(shù)作為代碼示例

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 代碼塊

根據(jù)官方文檔的解釋理解的意思:當(dāng)?shù)膶ο蟮瓴榭諘r,位于else的語句將會執(zhí)行,而如果在for循環(huán)里有break時,則會直接終止循環(huán),并不會執(zhí)行else里的代碼

寫一個簡單例子,用來輔助理解

for i in range(10): if i == 7:print(’found it %s’%i)breakelse: print(’not found’)

可以先運行代碼,看一下運行結(jié)果,然后將代碼塊里的break注釋掉再運行一遍,與第一次運行的結(jié)果進(jìn)行比較,就會發(fā)現(xiàn)不同

補(bǔ)充:python中for—else的用法,執(zhí)行完for執(zhí)行else

結(jié)束for循環(huán)后執(zhí)行else

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

Python中for后接else的語法使用

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 欧美一级二级三级视频 | 欧美一区二区三区不卡 | 久久99免费 | 国产精品综合在线 | 欧美视频中文字幕 | 第一页国产| 日韩伊人网 | 午夜影视av | 男人阁久久 | 久久久精品免费观看 | 日韩成人午夜 | 日韩久久久久久久久 | 亚洲欧美日韩国产一区 | www日本高清视频 | 丁香婷婷亚洲 | 美日韩中文字幕 | 午夜视频成人 | 亚洲色诱| 99热青青草 | 亚洲美女福利视频 | 亚洲欧美在线免费观看 | 99热只有这里有精品 | 四虎国产精品永久免费观看视频 | 亚洲精品亚洲 | 亚洲欧美日韩精品久久亚洲区 | a视频在线观看 | 色无极影院亚洲 | 国产一区二区三区18 | 成年人视频网站 | 成人高潮片免费视频 | 中国精品毛片 | 波多野结衣成人在线 | 亚洲乱熟| 性瑜伽xxxtⅴ | 日本精品成人 | av密臀 | 调教驯服丰满美艳麻麻在线视频 | 亚洲午夜小视频 | 日本成人一级片 | 亚洲资源在线观看 | www中文字幕在线观看 |