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

Time:05-23

I'm currently taking a 100 day python course and I am at the BMI calculator part 2. Here is the code I created:

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  ".")

This is the error I am getting :

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

CodePudding user response:

When your code is identically indented as you have shown then a BMI over 18.5 will result in no category being set. I am also assuming this is not your whole code as none of the categories that you want to print are actually defined.

For it to work you need indent it correctly (I also added an elif for the second case):

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  ".")

For the code to be executable you can just wrap each of your categories in " --> e.g.: category = "slightly_overweight"

  • Related