Python计算身体质量指数BMI

追求简洁之美

一道练习题,看到标准答案后,反思自己写的过于复杂了。

 

题目:

计算BMI值并打印分类

BMI = 体重 (kg) /身高2(m2)

分类 国际BMI值 国内BMI值
偏瘦 <18.5 <18.5
正常 18.5 - 25 18.5 - 24
偏胖 25 - 30 24 - 28
肥胖 >=30

>=28

输入

1.68,41

输出

‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬BMI 数值为:14.53
BMI 指标为:国际'偏瘦', 国内'偏瘦'

 

我的答案:

h,w = eval(input())#注意eval()转成数字以运算
BMI = w/pow(h,2)#注意公式中变量不要写反
print('BMI数值为:{0:.2f}'.format(BMI))#{.2f}不正确
s = ['偏瘦','正常','偏胖','肥胖']#描述string
c = ['BMI指标为:国际','国内']#classify
if BMI < 18.5:
    print("{0}'{1}',{2}'{1}'".format(c[0],s[0],c[1]))
elif BMI <= 24:
    print("{0}'{1}',{2}'{1}'".format(c[0],s[1],c[1]))
elif 24 < BMI <= 25:
    print("{0}'{1}',{2}'{3}'".format(c[0],s[1],c[1]),s[2])
elif 25 < BMI < 28:
    print("{0}'{1}',{2}'{1}'".format(c[0],s[2],c[1]))
elif 28 <= BMI < 30:
    print("{0}'{1}',{2}'{3}'".format(c[0],s[2],c[1]),s[3])
elif BMI >= 30:
    print("{0}'{1}',{2}'{1}'".format(c[0],s[3],c[1]))

标准答案:

height, weight = eval(input())
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who, nat = "", ""
if bmi < 18.5:
    who, nat = "偏瘦", "偏瘦"
elif 18.5 <= bmi < 24:
    who, nat = "正常", "正常"
elif 24 <= bmi < 25:
    who, nat = "正常", "偏胖"
elif 25 <= bmi < 28:
    who, nat = "偏胖", "偏胖"
elif 28 <= bmi < 30:
    who, nat = "偏胖", "肥胖"
else:
    who, nat = "肥胖", "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))

 

你可能感兴趣的:(Python学习笔记)