1

Python Version : 2.7

Just wondering what is wrong with the following code :

def bmi_cat(bmi):
    if bmi < 18.5:
        return "underweight"
    elif (bmi >=18.5 or bmi < 25):
        return "normal"
    elif (bmi >=25 or bmi < 30):
        return "overweight"
    else:
        return "obese"

Basically if i enter 17 it gives me the correct answer, but it gives me normal for anything above 18.5 (3000 gives normal instead of obese,etc...)

1
  • 2
    python allows you to write your conditionals as 18.5 <= bmi < 25, for increased readability and clarity
    – dm03514
    Sep 18, 2013 at 22:41

4 Answers 4

6

You want and not or... it needs to meet both criteria... You can also write it in Python as if 18.5 <= bmi < 25 to make it clearer and avoid this...

Also consider looking at http://docs.python.org/2/library/bisect.html which can do this sort of thing for you and will scale better if you had larger ranges. Take a look at the grade example.

4

It's because you're using or. If bmi >= 18.5 is true then the whole condition of the first elif will be true. Use and instead.

Or better yet, don't include two conditions in one. When the first elif is reached, you know that bmi >= 18.5, if it wasn't then the first if would have been entered. Hence, we can rewrite this as

if bmi < 18.5:
    return "underweight"
if bmi < 25:
    return "normal"
if bmi < 30:
    return "overweight"
return "obese"

We also don't need elif because return ends the function.

2
  • When the first elif is reached, you know that bmi >= 18.5, not that bmi > 25.
    – Air
    Sep 18, 2013 at 22:44
  • @AirThomas That's absolutely right, just a typo. Anyway, corrected.
    – arshajii
    Sep 19, 2013 at 0:09
2

It should be:

def bmi_cat(bmi):
    if bmi < 18.5:
        return "underweight"
    elif (bmi >=18.5 and bmi < 25):
        return "normal"
    elif (bmi >=25 and bmi < 30):
        return "overweight"
    else:
        return "obese"

If you check:

elif (bmi >=18.5 or bmi < 25):

it gives True for every value bigger or equal to 18.5

1
  • There are better explanations below and in practice you should definitely use @arshajii code instead my corrections.
    – zero323
    Sep 18, 2013 at 22:44
1

>= means "greater than or equals". So bmi >= 18.5 will be true for any number that is equal to 18.5 or above.

Because you've used the Boolean operator or, the whole statement will be true if the number is 18.5 or above. Hence why it works for 3000.

You probably meant to do bmi >= 18.5 and bmi <25, which will be True if both conditions are True.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.