Python中for后接else的語法使用
0、背景
今天看到了一個比較詭異的寫法,for后直接跟了else語句,起初還以為是沒有縮進好,查詢后發(fā)現(xiàn)果然有這種語法,特此分享。之前寫過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?
可以發(fā)現(xiàn),在for正常結束后,break中的語句進行了執(zhí)行。
# 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出了循環(huán),然后else當中的語句就沒有執(zhí)行。
2、總結
總結起來比較簡單,如果for循環(huán)正常結束,else中語句執(zhí)行。如果是break的,則不執(zhí)行。
工程性代碼寫的比較少,暫時沒有想到很好的場景,為了不對其他同學造成干擾,這種形式還是少些一點較好。
官方文檔也有解釋:
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的搭配
用找質數(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 代碼塊
根據官方文檔的解釋理解的意思:當?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) break else: print('not found')
可以先運行代碼,看一下運行結果,然后將代碼塊里的break注釋掉再運行一遍,與第一次運行的結果進行比較,就會發(fā)現(xiàn)不同
補充:python中for—else的用法,執(zhí)行完for執(zhí)行else
結束for循環(huán)后執(zhí)行else
for i in range(5): print(i) else: print("打印else")
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
深入探討PythonLogging模塊的高級用法與性能優(yōu)化
在Python應用程序中,日志處理是一項至關重要的任務,本文將探索Logging模塊的高級用法,包括日志級別、格式化、處理程序等方面的功能,需要的可以參考下2024-04-04python使用pandas處理excel文件轉為csv文件的方法示例
這篇文章主要介紹了python使用pandas處理excel文件轉為csv文件的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Python多進程入門、分布式進程數(shù)據共享實例詳解
這篇文章主要介紹了Python多進程入門、分布式進程數(shù)據共享,結合實例形式詳細分析了Python進程操作技巧數(shù)據共享相關實現(xiàn)技巧與注意事項,需要的朋友可以參考下2019-06-06詳解python如何在django中為用戶模型添加自定義權限
這篇文章主要介紹了python如何在django中為用戶模型添加自定義權限,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10