一、條件測試
每條 if 語句的核心都是一個值為 True 或 False 的表達式,這種表達式被稱為 條件測試,常見的比較有以下幾種
檢查是否相等:大多數(shù)條件測試都將一個變量的當前值同特定值進行比較。最簡單的條件測試檢查變量的值是否與特定值相等
檢查是否相等時不考慮大小寫:在 Python 中檢查是否相等時區(qū)分大小寫,兩個大小寫不同的值會被視為不相等
檢查是否不相等:要判斷兩個值是否不等,可結(jié)合使用驚嘆號和等號( != ),其中的驚嘆號表示 不
比較數(shù)字:相等或者不相等
檢查多個條件:使用 and 檢查多個條件,要檢查是否兩個條件都為 True ,可使用關(guān)鍵字 and 將兩個條件測試合而為一;如果每個測試都通過了,整個表達式就為 True :如果至少有一個測試沒有通過,整個表達式就為 False
使用 or 檢查多個條件:關(guān)鍵字 or 也能夠讓你檢查多個條件,但只要至少有一個條件滿足,就能通過整個測試。僅當兩個測試都沒有通過時,使用 or 的表達式才為 False
檢查特定值是否包含在列表中
要判斷特定的值是否已包含在列表中,可使用關(guān)鍵字 in
檢查特定值是否不包含在列表中
還有些時候,確定特定的值未包含在列表中很重要;在這種情況下,可使用關(guān)鍵字 not in
二、if 語句
2.1簡單的if語句
最簡單的 if 語句只有一個測試和一個操作
if的條件為真,就會執(zhí)行下面的操作
score=61
if score>=60:
print("You got a passing grade")
在 if 語句中,縮進的作用與 for 循環(huán)中相同。如果測試通過了,將執(zhí)行 if 語句后面所有縮進的代碼行,否則將忽略它們
score=61
if score>=60:
print("Congratulations on your")
print("You got a passing grade")
2.2if-else 語句
if-else 語句塊類似于簡單的 if 語句,但其中的 else 語句讓你能夠指定條件測試未通過時要執(zhí)行的操作
score=59
if score>=60:
print("Congratulations on your")
print("You got a passing grade")
else:
print('Sorry, please try harder next time')
2.3 if-elif-else 結(jié)構(gòu)
多個條件判斷
score=81
if 80>score>=60:
print("Congratulations on your")
print("You got a passing grade")
elif score>=80:
print("Your grades are excellent")
else:
print('Sorry, please try harder next time')
2.3使用多個 elif 代碼塊
score=91
if 80>score>=60:
print("Congratulations on your")
print("You got a passing grade")
elif 90>score>=80:
print("Your grades are average")
elif 90<score<= 100:
print("Your grades are excellent")
else:
print('Sorry, please try harder next time')
2.5省略 else 代碼塊
score=59
if 80>score>=60:
print("Congratulations on your")
print("You got a passing grade")
elif 90>score>=80:
print("Your grades are average")
elif 90<score<= 100:
print("Your grades are excellent")
print('Sorry, please try harder next time')
2.6檢查多個條件
有時候必須檢查你關(guān)心的所有條件,這個時候教使用多個if語句了
fruit=['grapes','banana','strawberry','apple','orange']
if 'grapes' in fruit:
print("Please give me some grapes")
if 'banana' in fruit:
print("Please give me some banana")
if 'strawberry' in fruit:
print("Please give me some strawberry")
三、使用 if 語句處理列表
3.1檢查特殊元素
fruits=['grapes','banana','strawberry','apple','orange','Mango.']
for fruit in fruits:
if fruit == 'Mango.':
print("Allergic to mangoes")
else:
print('Please give me some'+ ' '+fruit)
3.2確定列表不是空的
fruits=[]
if fruits:
for fruit in fruits:
if fruit == 'Mango.':
print("Allergic to mangoes")
else:
print('Please give me some'+ ' '+fruit)
else:
print("Would you like some fruit?")
3.3使用多個列表
fruits=['grapes','banana','strawberry','apple','orange','tomatoes']
vegetables=['cucumber','tomatoes','cantaloup']
for fruit in fruits:
if fruit in vegetables:
print(fruit + "is not a fruit")
else:
print('Please give me some'+ ' '+fruit)