第五章
1、一個簡單示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# 輸出:
Audi
BMW
Subaru
Toyota
上述例子遍歷一個汽車名的列表,并以首字母大寫的方式打印出來,但是當(dāng)遇到“bmw”的時候,就要全部字母大寫打印。
2、條件測試
每條if語句的核心都是一個值為True或False的表達(dá)式,這種表達(dá)式被稱為條件測試。Python根據(jù)條件測試的值為True還是False來決定是否執(zhí)行if語句中的代碼。如果條件測試的值為True,Python就執(zhí)行緊跟在if語句后面的代碼;如果為False,Python就忽略這些代碼。
(1)檢查是否相等
大多數(shù)條件測試都是將一個變量的當(dāng)前值同特定值進(jìn)行比較。比較兩個值是否相等,用兩個等號(==)來比較。若兩邊的值相等,返回True,否則返回False。
(2)檢查是否相等大小寫的問題
在Python中檢查大小寫是區(qū)分大小寫的,即同樣的單詞,大寫與小寫相比較的結(jié)果是不等的。
如果要進(jìn)行大小寫不重要的相等比較時,可以用字符串中的方法對其進(jìn)行相應(yīng)的處理再進(jìn)行比較。網(wǎng)站采用類似的方式讓用戶輸入的數(shù)據(jù)符合特定的格式,比如確保每個用戶名都是獨一無二的,當(dāng)你用相應(yīng)的大寫或者小寫進(jìn)行用戶名注冊時,就會遭到拒絕。
(3)檢查是否不相等
判斷兩個值是否不等,用感嘆號和等號(!=)來比較。兩邊的值不相等時,返回True,否則返回False。合理有效的使用(==)和(!=),可以提高一定的效率。
(4)比較數(shù)字
比較數(shù)字中,除了比較等于和不等于,還有小于(<)、小于等于(<=)、大于(>)、大于等于(>=)等等,當(dāng)條件成立時,返回True,否則返回False。
(5)檢查多個條件
使用and檢查多個條件:
當(dāng)要檢查是否兩個條件都為True時,可以使用關(guān)鍵字and將兩個條件測試合二為一;如果兩個條件都為True,則整個表達(dá)式就為True;如果至少有一個條件為False,整個表達(dá)式就為False。如檢查是否兩個人都不小于21歲:
age_0 = 22
age_1 = 18
print((age_0 >= 21) and (age_1 >= 21))
# 輸出:
False
age_0 = 22
age_1 = 25
print((age_0 >= 21) and (age_1 >= 21))
# 輸出:
True
使用or檢查多個條件:
關(guān)鍵字or只要至少有一個條件為True,整個表達(dá)式就為True。只有當(dāng)兩個條件都為False時,整個表達(dá)式才為False。
age_0 = 22
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21))
# 輸出:
True
age_0 = 20
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21))
# 輸出:
False
(6)檢查特定值是否包含在列表中
可使用關(guān)鍵字in來判斷特定的值是否包含在列表中。
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
# 輸出:
True
False
(7)檢查特定值是否不包含在列表中
使用關(guān)鍵字not in來判斷特定的值是否不包含在列表中。
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' not in requested_toppings)
print('pepperoni' not in requested_toppings)
# 輸出:
False
True
(8)布爾表達(dá)式
布爾表達(dá)式,就是條件測試的別名。與條件表達(dá)式一樣,它的結(jié)果不是True就是False。布爾值通常用于記錄條件。
game_active = True
3、if 語句
(1)簡單的 if 語句
最簡單的 if 語句只有一個測試和一個操作。
age = 20
if age >= 18:
print('You are old enough to vote!')
# 輸出:
You are old enough to vote!
在 if 語句中,縮進(jìn)的作用與for循環(huán)中的作用一樣。如果測試通過了,將執(zhí)行 if 語句后面所有縮進(jìn)的代碼行,否則將忽略它們。在緊跟在 if 語句后面的代碼塊中,可根據(jù)需要包含任意數(shù)量的代碼行。
(2)if-else語句
當(dāng)在條件測試中,若要在通過時執(zhí)行一個操作,沒通過時執(zhí)行另外一個操作,可使用 if-else 語句。
age = 16
if age >= 18:
print('You are old enough to vote!')
else:
print('Sorry, you are too young to vote.')
# 輸出:
Sorry, you are too young to vote.
if-else語句適合用于只有兩種情形的判斷,如上述代碼中,條件成立,執(zhí)行 if 后的語句,若不成立,則執(zhí)行else后的語句。
(3)if-elif-else 結(jié)構(gòu)
當(dāng)條件測試的結(jié)果超過兩種情形,可使用 if-elif-else 結(jié)構(gòu)。Python只執(zhí)行結(jié)構(gòu)中的一個代碼塊,它依次檢查每個條件測試,直到遇到了通過了的條件測試。測試通過后,Python將執(zhí)行緊跟在它后面的代碼,并跳過余下的代碼。其中的elif代碼塊可根據(jù)需要添加任意數(shù)量。如游樂園的門票問題:
age = 15
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 8
print('Your admission cost is $' + str(price) + '.')
# 輸出:
Your admission cost is $5.
(4)省略else代碼塊
Python并不要求 if 語句后面必須要有else代碼塊。else是一條包羅萬象的語句,只要不滿足任何if或elif中的條件測試,其中的代碼就會執(zhí)行,這可能會引入無效甚至惡意的數(shù)據(jù)。如果知道最終要測試的條件,應(yīng)考慮使用一個elif代碼塊來代替else代碼塊。這樣,你就可以肯定,僅當(dāng)滿足相應(yīng)的條件時,你的代碼才會執(zhí)行。
(5)測試多個條件
當(dāng)你需要檢查每一個條件時,就應(yīng)使用一系列不包含elif和else代碼塊的簡單 if 語句。在可能有多個條件為True,且你需要在每個條件為True時都采取相應(yīng)的措施時,適合使用這種方法。如披薩店中顧客點配料的例子中:
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print('Adding mushrooms.')
if 'pepperoni' in requested_toppings:
print('Adding pepperoni.')
if 'extra cheese' in requested_toppings:
print('Adding extra cheese.')
print('Finished making your pizza!')
# 輸出:
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!
如果你想只執(zhí)行一個代碼塊,就使用if-elif-else結(jié)構(gòu);如果要運(yùn)行多個代碼塊,就使用一系列獨立的 if 語句。
4、使用 if 語句處理列表
(1)檢查特殊元素
繼續(xù)上述披薩店的例子,當(dāng)顧客點的配料用完時的處理:
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print('Sorry, we are out of green peppers right now.')
else:
print('Adding ' + requested_topping + '.')
print('Finished making your pizza!')
# 輸出:
Addingmushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
(2)確定列表不是空的
繼續(xù)上述例子,當(dāng)顧客沒有點任何配料時,列表是空的,此時,需要向顧客確認(rèn)一下。
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print('Adding' + requested_topping + '.')
print('Finished making your pizza!')
else:
print('Are you sure you want a plain pizza?')
# 輸出:
Are you sure you want a plain pizza?
(3)使用多個列表
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print('Adding ' + requested_topping + '.')
else:
print("Sorry, we don't have " + requested_topping + '.')
print('Finished making your pizza!')
# 輸出:
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.
Finished making your pizza!
(5)設(shè)置 if 語句的格式
在條件測試的格式設(shè)置方面,PEP 8提供的唯一建議是,在諸如==、>=和<=等比較運(yùn)算符兩邊各添加一個空格。這樣的空格不會影響Python對代碼的解讀,而只是讓閱讀代碼的人理解起來更容易,同時也更美觀。