条件判断
在python中,IF实现:
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 做更细致的判断:
age = 3
if age >= 18:
print("adult")
elif age >= 6:
print("teenager")
else:
print("kid")
elif是else if的缩写
input()返回的数据类型是str,str不能直接和整数比较,必须把str转换为整数。
s = input("birth:")
birth = int(s)
if birth < 2000:
print("00前")
else:
print("00后")
练习:根据BMI公式(体重除以身高的平方)计算BMI指数,并根据指数:
- 低于18.5:过轻
- 18.5-25:正常
- 25-28:过重
- 28-32:肥胖
- 高于32:严重肥胖
用if-elif判断并打印结果:
name = input("请输入您的姓名:")
height = float(input("请输入您的身高(米):"))
weight = float(input("请输入您的体重(千克):"))
bmi = weight / (height * height)
if bmi <18.5:
print(" %s ,您好!\n 您的BMI指数为 %.1f ," % (name,bmi), "您体重过轻!")
elif bmi <= 25:
print(" %s ,您好!\n 您的BMI指数为 %.1f ," % (name,bmi), "您体重正常!")
elif bmi <= 28:
print(" %s ,您好!\n 您的BMI指数为 %.1f ," % (name,bmi), "您体重过重!")
elif bmi <= 32:
print(" %s ,您好!\n 您的BMI指数为 %.1f ," % (name,bmi), "您有点肥胖!")
else :
print(" %s ,您好!\n 您的BMI指数为 %.1f ," % (name,bmi), "您太胖了!")