【筆記】Python | 05 | if語句 | 5.2 條件測試
阿新 • • 發佈:2022-03-19
條件測試
程式設計時需要根據條件決定採取怎樣的措施。請看下面的示例:
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bwm':
print(car.upper())
else:
print(car.title())
輸出效果:
>>>
Audi
Bmw
Subaru
Toyota
每條if語句的核心是一個值為Ture或False的表示式,這種表示式稱為條件測試。如果條件測試值為True,就執行if語句後面的程式碼,否則Python就忽視。
檢查是否相等
檢查是否相等時會考慮大小寫。如果大小寫不重要,可將變數的值轉換為小寫,再檢查。
car = 'Audi'
print(car.lower() == 'audi')
檢查不相等
要判斷兩個值是否不等,可以使用!=
,其中!
表示不
。
requested_toppings = 'mushroom'
if requested_toppings != 'anchovies':
print("Hold the anchovies!")
比較數字
檢查數字是否不相等
answer = 17 if answer != 42: print("That is not the correct answer. Please try again!")
輸出:
>>> That is not the correct answer. Please try again!
檢查多個條件
有時需要在兩個條件為True時才執行操作,有時僅需一個為True即可,此時需要用到關鍵字and
和or
.
使用and
檢查多個條件
answer = 17
answer_1 = 18
answer_2 =12
if answer_1 >= answer and answer_2 <= answer:
print("OK")
使用or
檢查多個條件
answer = 17 answer_1 = 18 answer_2 =12 if answer_1 > answer or answer_2 > answer: print("Fine")
檢查特定值是否包含在列表中
有時執行操作前,需要檢查列表中是否包含特定的值。例如,結束使用者的註冊過程前,可能需要檢查提供的使用者名稱是否已包含在使用者名稱列表中。在地圖程式中,可能需要檢查使用者的位置是否包含在已知位置列表中。要判斷特定的值是否包含在列表中,使用關鍵字in
。
requested_toppings = ['mushroom', 'onions', 'pineapple']
if 'mushroom' in requested_toppings:
print("We got mushrooms!")
if 'pepperoni' in requested_toppings:
print('We got pepperoni!')
else:
print("We gotta buy some pepperoni!")
檢查特定值是否不包含在列表中
要檢查特定的值是否不在列表中,使用關鍵字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.")