python 将生成BMI和类别用户福尔斯[重复]的函数

myss37ts  于 2023-04-04  发布在  Python
关注(0)|答案(2)|浏览(101)

此问题在此处已有答案

How can I read inputs as numbers?(10个答案)
两年前关闭了。
我试图编写一个代码来计算用户输入的个人BMI,这里是我卡住的地方,使用第二个循环程序应该遍历身体质量指数数组并调用另一个接受身体质量指数的函数(BMI)作为参数,并返回个体是体重不足、正常体重还是超重,最后,我想计算每个类别中的个人数量。我一直得到一个错误typeerror:'〉'在'str'和'int'的示例之间不支持解决方案。老实说,我甚至不知道我是否这样做是正确的,以获得我想要的输出。谢谢你的任何帮助。
下面是我得到的:

individuals = list()
    for i in range((int(input("Please enter the number of individuals you would like calculate BMIs for:")))):
        user = str(input("Please enter the names of the individuals one at a time: "))
        individuals.append(user)
    BMIs = []
    for user in individuals:
        print("Input for", user)
        height = int(input(user + ", in inches, how tall are they? "))
        weight = int(input(user + ", in pounds, how much do they weigh? "))
        BMIs.append(user  + "s, BMI is: " + str(weight * 703/height**2))
    
    for BMI in BMIs:
        if ( BMI <18.5):
            print(BMI, "underweight")
        elif ( BMI >= 18.5 and BMI < 30):
            print(BMI,"normal")
        elif ( BMI >=30):
            print(BMI,"severely overweight")
62o28rlo

62o28rlo1#

根据你的错误,你试图比较一个str(字符串)变量和一个int(整数)变量。这是因为当你迭代BMIs列表时,所有的BMI值都具有以下形式:"user's, BMI is number"
所以发生的比较是:"user's, BMI is number" > int(number)你正在将一个完整的字符串与一个数字进行比较,而python无法理解这一点。
你需要解析你的字符串,提取你的数字,然后比较它。
一种可能的方法是:BMI[BMI.rindex(" ")::]
所以这个循环

for BMI in BMIs:
        if ( BMI <18.5):
            print(BMI, "underweight")
        elif ( BMI >= 18.5 and BMI < 30):
            print(BMI,"normal")
        elif ( BMI >=30):
            print(BMI,"severely overweight")

转换为:

for BMI in BMIs:
        if (int(BMI[BMI.rindex(" ")::]) <18.5):
            print(BMI, "underweight")
        elif (int(BMI[BMI.rindex(" ")::]) >= 18.5 and int(BMI[BMI.rindex(" ")::]) < 30):
            print(BMI,"normal")
        elif (int([BMI.rindex(" ")::]) >=30):
            print(BMI,"severely overweight")

rindex方法返回字符串参数在字符串中最后一次出现的索引。string[::]表示法是一个简单的字符串切片。

dpiehjr4

dpiehjr42#

下面是将字符串附加到列表BMIs

BMIs.append(user  + "s, BMI is: " + str(weight * 703/height**2))

因此,当你进行比较时,Python会抛出一个错误。你需要做的是使用字典:

BMI = {}  # Create an empty dict here
    for user in individuals:
        print("Input for", user)
        height = int(input(user + ", in inches, how tall are they? "))
        weight = int(input(user + ", in pounds, how much do they weigh? "))
        BMI[user] = weight * 703/height**2

然后,您可以使用字典值进行比较:

for key, value in BMI.items():
        if BMI[key] < 18.5:
            print(f'{key} with BMI of {value} is underweight')
        elif BMI[key] >= 18.5 and BMI[key] < 30:
            print(f'{key} with BMI of {value} has normal weight.')
        elif BMI[key] >=30:
            print(f'{key} with BMI of {value} is overweight.')

另外,在Python的if语句中不需要使用方括号。

相关问题