这是我在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行,在 if float(bmi_user)&lt; 18:
ValueError:无法将字符串转换为float:
答案 0 :(得分:1)
错误消息很明确:您无法在字符串和双精度数据之间进行比较。
查看函数返回的内容:字符串。
Hist_2D
你会做得更好:
data [0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.429 0.143 0.000 0.000 0.048 0.000 0.000 0.000 0.000
0.857 0.810 0.667 0.429 0.429 0.286 0.190 0.286 0.143
0.952 0.952 0.905 0.857 0.857 0.905 0.857 0.762 0.810
1.000 1.000 0.952 0.952 0.952 0.952 0.952 0.952 1.000
1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000
1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000
1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000
1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000]
答案 1 :(得分: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
。
答案 2 :(得分: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