Python if语句语法?

时间:2013-10-14 00:52:01

标签: python if-statement

我正在研究一个BMI计算器,并为它的“状态”部分提供了一堆if语句。出于某种原因,我通过Eclipse收到错误说“预期:)”,但我不知道缺少什么。

以下是抛出错误的代码示例:

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"

4 个答案:

答案 0 :(得分:4)

正如其他答案中已经提到的那样,错误是由=>引起的,而&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"

答案 1 :(得分:3)

=>在Python中没有任何意义。而是“大于或等于”而是写成>=

答案 2 :(得分: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)

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:

仅当MyNumber为0到2之间的某个数字时,这将是Truthy。