user1804933
user1804933

Reputation: 453

Python if statement syntax?

I am working on a BMI calculator and have a bunch of if statements for the "status" part of it. For some reason I am getting an error through Eclipse saying that "Expected:)" but I have no clue what is missing.

Here is a sample of the code which is throwing the error:

BMI = mass / (height ** 2)

if(BMI < 18.5):
    status = "Underweight"

if(BMI => UNDERWEIGHT and BMI < NORMAL):
    status = "Normal"

if(BMI => NORMAL & BMI < OVERWEIGHT):
    status = "Overweight"

elif(BMI >= 30):
    status = "Obese"

Upvotes: 0

Views: 706

Answers (4)

Adam Morris
Adam Morris

Reputation: 8545

You might change:

if(BMI => NORMAL & BMI < OVERWEIGHT):

to:

if(BMI >= NORMAL and BMI < OVERWEIGHT):

With some of the other suggestions, you might re-write the entire statement as:

if BMI < UNDERWEIGHT:
    status = "Underweight"

elif BMI >= UNDERWEIGHT and BMI < NORMAL:
    status = "Normal"

elif BMI >= NORMAL and BMI < OVERWEIGHT:
    status = "Overweight"

elif BMI >= OVERWEIGHT:
    status = "Obese"

Upvotes: 2

Stuart
Stuart

Reputation: 9858

As already noted on other answers, the error is caused by =>, and & is a bitwise operator which is not what you want in this context. But as per @Blckknght's comment, you can probably simplify this anyway by only comparing to the maximum value each time. Also, get rid of the parentheses as these are not needed in Python.

BMI = mass / (height ** 2)    
if BMI < UNDERWEIGHT:
    status = "Underweight"
elif BMI < NORMAL:
    status = "Normal"
elif BMI < OVERWEIGHT:
    status = "Overweight"
else:
    status = "Obese"

Upvotes: 4

thefourtheye
thefourtheye

Reputation: 239443

BMI = mass / (height ** 2)

if (BMI < 18.5):
    status = "Underweight"
elif (UNDERWEIGHT < BMI < NORMAL):
    status = "Normal"
elif (NORMAL < BMI < OVERWEIGHT):
    status = "Overweight"
else
    status = "Obese"

In python we can check whether a number is in the range, like this

if 0 < MyNumber < 2:

This will be Truthy only when MyNumber is some number between 0 and 2.

Upvotes: 0

jwodder
jwodder

Reputation: 57460

=> does not mean anything in Python. "Greater than or equal to" is instead written >=.

Upvotes: 3

Related Questions