不确定为什么变量没有在我的 if / elif 语句中定义

Not sure why the variable isn't becoming defined in my if / elif statement

我目前正在参加为期 100 天的 python 课程,我正在学习 BMI 计算器第 2 部分。这是我创建的代码:

height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
BMI = round(weight / height ** 2, 1)
if BMI < 18.5:
    category = underweight
    if 18.5 >= BMI <= 25:
     category = normal_weight
    elif 25 >= BMI <= 30:
     category = slightly_overweight
    elif 30 >= BMI <= 35:
     category = obese
    elif BMI > 35:
     category = clinically_obese
print("Your BMI is " + str(BMI) + ", you are " +category+ ".")

这是我遇到的错误:

  File "main.py", line 18, in <module>
    print("Your BMI is " + str(BMI) + ", you are " +category+ ".")
NameError: name 'category' is not defined
➜ 

当您的代码与您显示的缩进相同时,BMI 超过 18.5 将导致未设置任何类别。 我还假设这不是您的全部代码,因为实际上定义了您要打印的 none 个类别。

要使其正常工作,您需要正确缩进(我还为第二种情况添加了 elif):

height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
BMI = round(weight / height ** 2, 1)
if BMI < 18.5:
    category = underweight
elif 18.5 >= BMI <= 25:
    category = normal_weight
elif 25 >= BMI <= 30:
    category = slightly_overweight
elif 30 >= BMI <= 35:
    category = obese
elif BMI > 35:
    category = clinically_obese
print("Your BMI is " + str(BMI) + ", you are " +category+ ".")

为了使代码可执行,您可以将每个类别包装在 " 中 --> 例如:category = "slightly_overweight"