婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > Python中for后接else的語法使用

Python中for后接else的語法使用

熱門標簽:富錦商家地圖標注 沈陽防封電銷卡品牌 如何申請400電話費用 江西省地圖標注 武漢外呼系統平臺 池州外呼調研線路 外呼系統哪些好辦 沈陽外呼系統呼叫系統 沈陽人工外呼系統價格

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跳出雙層嵌套循環的方法實例
  • Python for循環搭配else常見問題解決
  • python for和else語句趣談
  • Python中在for循環中嵌套使用if和else語句的技巧
  • Python的for和break循環結構中使用else語句的技巧

標簽:潛江 銅川 呂梁 阿里 黑龍江 通遼 株洲 常德

巨人網絡通訊聲明:本文標題《Python中for后接else的語法使用》,本文關鍵詞  Python,中,for,后接,else,的,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Python中for后接else的語法使用》相關的同類信息!
  • 本頁收集關于Python中for后接else的語法使用的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 夏邑县| 当涂县| 合山市| 宁远县| 正镶白旗| 曲靖市| 根河市| 五原县| 石狮市| 安达市| 永胜县| 巫溪县| 北京市| 武穴市| 临清市| 金堂县| 东阿县| 崇信县| 广西| 布尔津县| 无为县| 南丰县| 津南区| 高青县| 中西区| 甘孜县| 泰安市| 盐池县| 泗洪县| 卢龙县| 金川县| 通江县| 万源市| 道真| 七台河市| 邵武市| 东安县| 邢台县| 泽州县| 鸡西市| 资讯 |