如何修复这个Python BMI计算器?

问题描述 投票:0回答:3

这是我在python中编写的BMI计算器

print('BMI calculator V1')

name = str(input("What's your name?"))
weight = int(input("Your weight in Kilograms"))
height = float(input("Your height in Metres"))

def function(w, h):    #function here is the bmi calculator
     bmi = w / h ** 2
     return("Your BMI is " + str(bmi))

bmi_user = function(weight, height)  
print(bmi_user)  

if bmi_user < 18:
     print(name + "," + "you are underweight")
elif bmi_user > 25:
     print(name + "," + "you are overweight")
else:
     print(name + "," + "you are normal")

它在运行代码时显示以下错误

第15行,如果float(bmi_user)<18: ValueError:无法将字符串转换为float:

python debugging
3个回答
1
投票

错误消息很明确:您无法在字符串和double之间进行比较。

看看你的函数返回的内容:一个字符串。

def function(w, h):    #function here is the bmi calculator
     bmi = w / h ** 2
     return("Your BMI is " + str(bmi))

bmi_user = function(weight, height) 

你会做得更好:

def bmi_calculator(w, h):    
     return w / h ** 2 

1
投票

通过不从计算中返回字符串来修复它。您应该将此How to debug small programs (#1)读取并按照它来调试您的代码。

print('BMI calculator V1')

name = str(input("What's your name?"))
weight = int(input("Your weight in Kilograms"))
height = float(input("Your height in Metres"))

def calcBmi(w, h):    # function here is the bmi calculator
     bmi = w / h ** 2
     return bmi        # return a float, not a string

bmi_user = calcBmi(weight, height)  # now a float
print(f'Your BMI is: {bmi_user:.2f}')   # your output message

if bmi_user < 18:
     print(name + "," + "you are underweight")
elif bmi_user > 25:
     print(name + "," + "you are overweight")
else:
     print(name + "," + "you are normal")

function不是一个非常好的名字,我改为calcBmi


0
投票

你的函数def函数(w,h):返回一个字符串,如下所示。

return("Your BMI is " + str(bmi))

这不能与您在下面的语句中指定的整数进行比较。

if bmi_user < 18:

以下行也将是一个错误

elif bmi_user > 25:

如下更改您的功能,它将工作

def function(w, h):    #function here is the bmi calculator
    bmi = w / h ** 2
    return bmi
© www.soinside.com 2019 - 2024. All rights reserved.