2013-10-14 197 views
0

我正在研究一個BMI計算器,併爲它的「狀態」部分提供了一堆if語句。出於某種原因,我通過Eclipse發現錯誤「預計:)」,但我不知道缺少什麼。Python if語句的語法?

這裏是拋出錯誤的代碼示例:

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" 
+0

你在哪裏看到這個錯誤 –

回答

3

=>並不意味着在Python什麼。 「大於或等於」代替>=

+2

其值得注意的是,如果你使用第二和第三'if'語句'elif'和'else'最後一個,你就不需要做任何'> ='測試。另一個問題是在第三個測試中的&。 – Blckknght

2

您可以更改:

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

到:

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

隨着其他的一些建議,你可能會重新寫整個語句爲:

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" 
+3

你可能要考慮擺脫(和)。 –

+0

謝謝 - 更新。 –

0
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" 

在python中,我們可以檢查一個數字是否在範圍內,這樣

if 0 < MyNumber < 2: 

這將是Truthy只有當mynumber的是

+0

我認爲OP在幾個地方想要<=而不是<< – Stuart

4

如已經在其他的答案指出0和2之間的一些數量,錯誤是由=>引起的,並且&bitwise operator這是不你在這方面想要什麼。但是根據@Blckknght的評論,無論如何,只要每次比較最大值就可以簡化它。另外,請刪除括號,因爲Python中不需要這些括號。

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