前言
本文討論Python的for…else
和while…else
等語法,這些是Python中最不常用、最為誤解的語法特性之一。
Python中的for
、while
等循環(huán)都有一個可選的else
分支(類似if
語句和try
語句那樣),在循環(huán)迭代正常完成之后執(zhí)行。換句話說,如果我們不是以除正常方式以外的其他任意方式退出循環(huán),那么else
分支將被執(zhí)行。也就是在循環(huán)體內(nèi)沒有break
語句、沒有return
語句,或者沒有異常出現(xiàn)。
下面我們來看看詳細的使用實例。
一、 常規(guī)的 if else 用法
1
2
3
4
5
|
x = True if x: print 'x is true' else : print 'x is not true' |
二、if else 快捷用法
這里的 if else
可以作為三元操作符使用。
1
2
3
|
mark = 40 is_pass = True if mark > = 50 else False print "Pass? " + str (is_pass) |
三、與 for 關(guān)鍵字一起用
在滿足以下情況的時候,else
下的代碼塊會被執(zhí)行:
1、for
循環(huán)里的語句執(zhí)行完成
2、for
循環(huán)里的語句沒有被 break
語句打斷
1
2
3
4
5
6
7
8
9
10
11
12
|
# 打印 `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 關(guān)鍵字一起用
和上面類似,在滿足以下情況的時候,else
下的代碼塊會被執(zhí)行:
1、while
循環(huán)里的語句執(zhí)行完成
2、while
循環(huán)里的語句沒有被 break
語句打斷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# 打印 `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
里的語句就能被執(zhí)行。
1
2
3
4
5
6
7
8
9
|
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() |
總結(jié)
關(guān)于Python中循環(huán)語句中else的用法總結(jié)到這就基本結(jié)束了,這篇文章對于大家學(xué)習(xí)或者使用Python還是具有一定的參考借鑒價值的,希望對大家能有所幫助,如果有疑問大家可以留言交流。