二、判斷語句
1.if語句
格式:
if 要判斷的條件:
條件成立時要做的操作
注意隻有在縮進内的代碼才算在if條件成立要做的操作裡,如果沒有縮進,則不算
頂格書寫的代碼,代表與if沒有關系
2.if-else結構
格式:
if 條件:
條件
else:
條件
# 本例示範基本的if語句
# 使用者鍵盤輸入對應的年齡
age = input("請輸入您的年齡:")
# 判斷年齡是否大于18歲
if int(age)>18:
print("我已經成年了")
else:
print("我還沒成年")
print("if-else語句結束")
3.if elif條件
格式
if 條件1:
執行代碼
elif 條件2:
執行代碼
……
# 本例示範if-elif語句
# 使用者輸入成績
score = input("請輸入您的考試成績:")
# 将score轉換為int類型
score = int(score)
# 利用if-elif語句進行判斷
if score < 60:
print("成績等級為E")
elif (score >= 60) and (score < 70):
print("成績等級為D")
elif (score >= 70) and (score < 80):
print("成績等級為C")
elif (score >= 80) and (score < 90):
print("成績等級為B")
elif (score >= 90) and (score <= 100):
print("成績等級為A")
else:
print("您輸入的成績不合法")
print("代碼執行結束")
4.if語句嵌套
# 本例示範if語句的嵌套
age = input("請輸入您的年齡:")
age = int(age)
if age > 50:
if age > 80:
print("您的年齡大于80")
elif (age <= 80) and (age > 50):
print("您的年齡介于50到80歲之間")
elif (age <= 50) and (age > 0):
if age > 25:
print("您的年齡介于25-50之間")
elif (age <= 25) and (age >= 0):
print("您的年齡介于0到25歲之間")
else:
print("您輸入的年齡不合法")