Matt Walker
Matt Walker

Reputation: 181

Python if statement troubleshooting

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

Upvotes: 1

Views: 132

Answers (4)

arshajii
arshajii

Reputation: 129572

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.

Upvotes: 4

zero323
zero323

Reputation: 330453

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

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142256

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.

Upvotes: 6

TerryA
TerryA

Reputation: 60024

>= 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.

Upvotes: 1

Related Questions