五、if語句
5.1 一個簡單示例
使用if 語句來正確地處理特殊情形。
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
代碼輸出:
Audi
BMW
Subaru
Toyota
5.2 條件測試
每條if 語句的核心都是一個值為True 或False 的表達式,這種表達式被稱為條件測試 。
Python根據條件測試的值為True 還是False 來決定是否執行if 語句中的代碼。
如果條件測試的值為True ,Python就執行緊跟在if 語句后面的代碼;如果為False ,Python就忽略這些代碼。
5.2.1 檢查是否相等
大多數條件測試都將一個變量的當前值同特定值進行比較。
>>> car = 'bmw' >>> car = 'audi'
>>> car == 'bmw' >>> car == 'bmw'
True False
5.2.2 檢查是否相等時區分大小寫
在Python中檢查是否相等時區分大小寫。
>>> car = 'Audi'
>>> car == 'audi'
False
5.2.3 檢查是否不相等
要判斷兩個值是否不等,可結合使用驚嘆號和等號(!=),其中的驚嘆號表示不。
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
代碼輸出:
Hold the anchovies!
5.2.4 比較數字
檢查數值非常簡單。
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
5.2.5 檢查多個條件
1)使用and檢查多個條件
要檢查是否兩個條件都為True ,可使用關鍵字and 將兩個條件測試合而為一;
如果每個測試都通過了,整個表達式就為True ;
如果至少有一個測試沒有通過,整個表達式就為False 。
>>> age_0 = 22
>>> age_1 = 18
>>>(age_0 >= 21) and (age_1 >= 21)
False
2)使用or檢查多個條件
關鍵字 or 也能夠讓你檢查多個條件,但只要至少一個條件滿足,就能夠通過測試。
僅當兩個測試都沒有通過時,使用or的表達式才返回False。
>>> age_0 = 18
>>> (age_0 >= 21 )or (age_1 >= 21)
False
5.2.6 檢查特定值是否
要判斷特定的值是否已包含在列表中,可使用關鍵字in 。
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
5.2.7 檢查特定值是否不包含在列表中
確定特定的值未包含在列表中使用關鍵字not in 。
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
代碼輸出:
Marie, you can post a response if you wish.
5.2.8 布爾表達式
隨着你對編程的了解越來越深入,將遇到術語布爾表達式,布爾值通常用於記錄條件。
game_active = True
can_edit = False
5.3 if語句
5.3.1 簡單的if語句
最簡單的if 語句只有一個測試和一個操作:
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
代碼輸出:
You are old enough to vote!
Have you registered to vote yet?
注:在if 語句中,縮進的作用與for 循環中相同。如果測試通過了,將執行if 語句后面所有縮進的代碼行,否則將忽略它們。
5.3.2 if-else語句
在條件測試通過了時執行一個操作,並在沒有通過時執行另一個操作;在這種情況下,可使用Python提供的if-else 語句。
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
代碼輸出:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
注:if-else 結構非常適合用於要讓Python執行兩種操作之一的情形。
5.3.3 if-elif-else結構
經常需要檢查超過兩個的情形,為此可使用Python提供的if-elif-else 結構。
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
代碼輸出:
Your admission cost is $5.
5.3.4 使用多個elif代碼塊
可根據需要使用任意數量的elif 代碼塊。
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
5.3.5 省略else代碼塊
Python並不是要求if-elif結構后面必須有else代碼塊。
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
注:else 是一條包羅萬象的語句,只要不滿足任何if 或elif 中的條件測試,其中的代碼就會執行。
5.3.6 測試多個條件
有時候必須檢查你關心的所有條件,在這種情況下,應使用一系列簡單if 語句。
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("\nFinished making your pizza!")
代碼輸出:
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!
5.4 使用if語句處理列表
5.4.1 檢查特殊元素
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("\nFinished making your pizza!")
代碼輸出:
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
5.4.2 確定列表不是空的
檢查列表元素是否為空
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
注:如果requested_toppings 不為空就運行for 循環;否則就打印一條消息。
5.4.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("\nFinished making your pizza!")
代碼輸出:
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.
Finished making your pizza!
5.5 設置if語句的格式
PEP 8提供的唯一建議是,在諸如== 、>= 和<= 等比較運算符兩邊各添加一個空格。if age < 4: 要比if age<4: 好。