条件判断出错案例

刚开始学习python,看的教程是廖大的,条件判断那一章的练习题如下

小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:

  • 低于18.5:过轻
  • 18.5-25:正常
  • 25-28:过重
  • 28-32:肥胖
  • 高于32:严重肥胖

if-elif判断并打印结果


程序如下:

weight = input('weight:')
height = input('height:')
bmi = weight/(height*height)
if bmi < 18.5:
    print('瘦子')
elif bmi <25:
    print('鲜肉')
elif bmi <28:
    print('胖子')
elif bmi <32:
    print('大胖子')
else:
    print('死胖子')



运行时报错:

Traceback (most recent call last):
  File "new1.py", line 23, in <module>
    bmi = weight/(height*height)

TypeError: can't multiply sequence by non-int of type 'str'


通过上网百度是因为input默认字符串形式,需要强转成int型。

修改成以下:

bmi = int(weight)/(int(height)*int(height))

其它不变,

结果运行如下

    

猜你喜欢

转载自blog.csdn.net/tlyhjfs/article/details/79494366