Home > Enterprise >  Unknown syntax error when coding boolean logic
Unknown syntax error when coding boolean logic

Time:04-28

I am trying to make a BMI calculator but keep getting a syntax error for line 6 every time I run it. Line 5 is similar and runs with no problem. I recently made the BMI variable a float and an integer to see if that was my problem, but I just can't seem to figure it out.

h = float(int(input()))
w = int(input)
bmi = float(int(w / ( h ** 2)))
if bmi < 18.5:
    print(Underweight)
elif bmi >= 18.5 and < 25:
    print(Normal)
elif bmi >= 25 and < 30:
    print(Overweight)
if bmi > 30: 
    print(Obesity)

CodePudding user response:

In English you can say "if bmi is greater than 18.5 and less than 25", and everyone will know that "less than 25" still refers to bmi.

Python is not that good at context though, so you have to clarify that:

elif bmi >= 18.5 and bmi < 25:

You will then run into a series of other minor issues:

  • Make sure to use input() instead of just input so that the function is invoked.
  • Use print("Underweight") with quotes to clarify that this is a string and not a variable name
  • float(int(..)) doesn't make much sense because by then you've already truncated the value, so just use float(..)

All together, you'd end up with:

h = float(input())
w = int(input())
bmi = float(w / ( h ** 2))
if bmi < 18.5:
    print("Underweight")
elif bmi >= 18.5 and bmi < 25:
    print("Normal")
elif bmi >= 25 and bmi < 30:
    print("Overweight")
if bmi > 30: 
    print("Obesity")

If you wanted to, you could further simplify it by taking advantage of the fact that your calculation is already in floats and only one branch of an if..elif..else statement will be taken, to get:

h = float(input())
w = int(input())
bmi = w / ( h ** 2)
if bmi < 18.5:
    print("Underweight")
elif bmi < 25:
    print("Normal")
elif bmi < 30:
    print("Overweight")
else:
    # BMI is necessarily > 30 here, otherwise one of the
    # other branches would have triggered already
    print("Obesity")

CodePudding user response:

You need to add ''' bmi<25 ''' instead of ''' <25 '''.

h = float(int(input()))
w = int(input)
bmi = float(int(w / ( h ** 2)))
if bmi < 18.5:
    print(Underweight)
elif bmi >= 18.5 and bmi < 25:
    print(Normal)
elif bmi >= 25 and bmi < 30:
    print(Overweight)
if bmi > 30:
    print(Obesity)
  • Related