[英]How to fix this Python BMI calculator?
This is a BMI calculator that I wrote in python 这是我用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")
It shows the following error when I run the code 运行代码时显示以下错误
line 15, in if float(bmi_user) < 18:
第15行,如果float(bmi_user)<18:
ValueError: could not convert string to float:ValueError:无法将字符串转换为float:
The error message is clear: You can't do comparisons between a string and a double. 错误消息很清楚:您不能在字符串和双精度之间进行比较。
Look at what your function returns: a string. 查看函数返回的内容:字符串。
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)
You'll do better with this: 您可以通过以下方法做得更好:
def bmi_calculator(w, h):
return w / h ** 2
Fix it by not returning a string from your calculation. 通过不从计算中返回字符串来修复它。 You should give this How to debug small programs (#1) a read and follow it to debug your code.
您应该阅读此“ 如何调试小型程序(#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
is not a really good name, I changed it to calcBmi
. function
不是一个好名字,我将其更改为calcBmi
。
Your function def function(w, h): returns a string as below. 您的函数def function(w,h):返回如下字符串。
return("Your BMI is " + str(bmi))
This cannot be compared with an integer as specified in your statements like below. 不能将其与以下语句中指定的整数进行比较。
if bmi_user < 18:
The below line also will be an error 下一行也将是一个错误
elif bmi_user > 25:
Change your function as below, it will work 如下更改您的功能,它将起作用
def function(w, h): #function here is the bmi calculator
bmi = w / h ** 2
return bmi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.