Home > Software engineering >  use of < var < in embedded if statements
use of < var < in embedded if statements

Time:11-26

i'm learning python via Udemy and we did a coding project where you have to get a user's height and weight, calculate their BMI and print the result. in my code, for the embedded if (elif) statements, i did something like this (variable is bmi to hold the actual BMI calculation): elif 18.5 < bmi < 25

if bmi < 18.5:
  print(f"Your BMI is {bmi}, you are slightly underweight.")
elif 18.5 < bmi < 25:
  print(f"Your BMI is {bmi}, you have a normal weight.")
elif 25 < bmi < 30:
  print(f"Your BMI is {bmi}, you are slightly overweight.")

now, the instructor instead did this: elif bmi < 25
she didn't use the format < var < like i did. now my code worked just fine from what i can tell but it was implied that there could be a potential issue using my format. can anyone confirm/deny that my format could cause a problem under the right circumstances???

i just want to make sure i'm coding correctly

CodePudding user response:

now, the instructor instead did this: elif bmi < 25

This is better for two reasons:

  1. You already know bmi >= 18.5 because if it were lower you would have entered the first if clause and not reached this elif test. So it's a waste of effort to test again whether for bmi > 18.5

  2. If bmi is exactly equal to 18.5, none of your tests will match and your code will probably do something unexpected. You should be testing for bmi >= 18.5 (which again is redundant because of point 1), or including an elif clause specifically to check bmi == 18.5 if that case needs special handling.

CodePudding user response:

x < bmi < y is perfectly fine Python code. Python will interpret it as x < bmi and bmi < y:

https://www.geeksforgeeks.org/chaining-comparison-operators-python/

However, as @The Photon said, your code will have a bug if you input bmi = 18.5 or 25.

Since if, elif, ... statements are evaluated in sequence, it's better to avoid introducing bugs, and work as your intructor did (if bmi < 25, etc.), because you already know that this line of code will only execute after the previous if/elif expressions failed (like if bmi < 18.5).

  • Related