條件判斷
在python中低滩,IF實(shí)現(xiàn):
age = 20
if age >= 18
print("your age is", age)
print("adult")
age = 3
if age >= 18:
print("your age is", age)
print("adult")
else:
print("your age is", age)
print("teenager")
注意不要少些冒號:
還可以用elif 做更細(xì)致的判斷:
age = 3
if age >= 18:
print("adult")
elif age >= 6:
print("teenager")
else:
print("kid")
elif是else if的縮寫
input()返回的數(shù)據(jù)類型是str包蓝,str不能直接和整數(shù)比較,必須把str轉(zhuǎn)換為整數(shù)。
s = input("birth:")
birth = int(s)
if birth < 2000:
print("00前")
else:
print("00后")
練習(xí):根據(jù)BMI公式(體重除以身高的平方)計(jì)算BMI指數(shù),并根據(jù)指數(shù):
- 低于18.5:過輕
- 18.5-25:正常
- 25-28:過重
- 28-32:肥胖
- 高于32:嚴(yán)重肥胖
用if-elif判斷并打印結(jié)果:
name = input("請輸入您的姓名:")
height = float(input("請輸入您的身高(米):"))
weight = float(input("請輸入您的體重(千克):"))
bmi = weight / (height * height)
if bmi <18.5:
print(" %s ,您好母谎!\n 您的BMI指數(shù)為 %.1f ," % (name,bmi), "您體重過輕!")
elif bmi <= 25:
print(" %s ,您好京革!\n 您的BMI指數(shù)為 %.1f ," % (name,bmi), "您體重正常奇唤!")
elif bmi <= 28:
print(" %s ,您好!\n 您的BMI指數(shù)為 %.1f ," % (name,bmi), "您體重過重匹摇!")
elif bmi <= 32:
print(" %s ,您好咬扇!\n 您的BMI指數(shù)為 %.1f ," % (name,bmi), "您有點(diǎn)肥胖!")
else :
print(" %s ,您好廊勃!\n 您的BMI指數(shù)為 %.1f ," % (name,bmi), "您太胖了懈贺!")