前言
本文討論Python的
for…else
和
while…else
等語法,這些是Python中最不常用、最為誤解的語法特性之一。
Python中的
for
、
while
等循環都有一個可選的
else
分支(類似
if
語句和
try
語句那樣),在循環迭代正常完成之后執行。換句話說,如果我們不是以除正常方式以外的其他任意方式退出循環,那么
else
分支將被執行。也就是在循環體內沒有
break
語句、沒有
return
語句,或者沒有異常出現。
下面我們來看看詳細的使用實例。
一、 常規的 if else 用法
x = True if x: print 'x is true' else: print 'x is not true'
二、if else 快捷用法
這里的
if else
可以作為三元操作符使用。
mark = 40 is_pass = True if mark >= 50 else False print "Pass? " + str(is_pass)
三、與 for 關鍵字一起用
在滿足以下情況的時候,
else
下的代碼塊會被執行:
???? 1、
for
循環里的語句執行完成
???? 2、
for
循環里的語句沒有被
break
語句打斷
# 打印 `For loop completed the execution` for i in range(10): print i else: print 'For loop completed the execution' # 不打印 `For loop completed the execution` for i in range(10): print i if i == 5: break else: print 'For loop completed the execution'
四、與 while 關鍵字一起用
和上面類似,在滿足以下情況的時候,
else
下的代碼塊會被執行:
???? 1、
while
循環里的語句執行完成
???? 2、
while
循環里的語句沒有被
break
語句打斷
# 打印 `While loop execution completed` a = 0 loop = 0 while a <= 10: print a loop += 1 a += 1 else: print "While loop execution completed" # 不打印 `While loop execution completed` a = 50 loop = 0 while a > 10: print a if loop == 5: break a += 1 loop += 1 else: print "While loop execution completed"
五、與 try except 一起用
和
try except
一起使用時,如果不拋出異常,
else
里的語句就能被執行。
file_name = "result.txt" try: f = open(file_name, 'r') except IOError: print 'cannot open', file_name else: # Executes only if file opened properly print file_name, 'has', len(f.readlines()), 'lines' f.close()
總結
關于Python中循環語句中else的用法總結到這就基本結束了,這篇文章對于大家學習或者使用Python還是具有一定的參考借鑒價值的,希望對大家能有所幫助,如果有疑問大家可以留言交流。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
