Can anyone explain why this worked? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone explain why this worked?

My code for BMI calculator: weight = int(input()) height = float(input()) bmi = float(weight / (height ** 2)) if bmi < 18.5: print("Underweight") elif 18.5 >= bmi < 25: print("Normal") elif 25 >= bmi < 30: print("Overweight") else: print("Obesity") This cleared the 2 visible test cases but not the hidden ones. The code that cleared all the test cases: weight = int(input()); height = float(input()); bmi = weight / float(height ** 2); if bmi<18.5: print('Underweight') elif bmi>=18.5 and bmi<25: print("Normal") elif bmi>=25 and bmi<30: print('Overweight') else: print('Obesity') Why did adding another float() cleared those cases?

5th Nov 2021, 1:27 PM
Faiz Shaikh
Faiz Shaikh - avatar
5 Answers
+ 6
the comparison in the if... construct can also be done like this: weight = float(input()) height = float(input()) bmi = weight / (height * height) if bmi < 18.8: print("Underweight") elif bmi < 25: print("Normal") elif bmi < 30: print("Overweight") else: print("Obesity")
5th Nov 2021, 4:32 PM
Lothar
Lothar - avatar
+ 3
Hi Faiz! Using float() isn't the reason your first code is not working. It's not working because you used interval comparison in wrong format. You may check that once. It needs to be like this 18.5 <= bmi < 25 And the same goes to the next condition
5th Nov 2021, 1:57 PM
Python Learner
Python Learner - avatar
+ 2
If you read the task instruction carefully, you'll find that input is float for height
5th Nov 2021, 1:39 PM
Lisa
Lisa - avatar
+ 1
My bad I wrote it wrong here, now It's edited
5th Nov 2021, 1:44 PM
Faiz Shaikh
Faiz Shaikh - avatar
+ 1
Hey JUMP_LINK__&&__Python__&&__JUMP_LINK Learner , I think the comparison is right as the question states: Underweight = less than 18.5 Normal = more or equal to 18.5 and less than 25 Overweight = more or equal to 25 and less than 30 Obesity = 30 or more
5th Nov 2021, 2:04 PM
Faiz Shaikh
Faiz Shaikh - avatar