Reputation: 33
I've built the following code:
# function to calculate bmi and return a result based on user input
def calculatebmi(weight, height):
bmivalue = weight // (height ** 2)
if bmivalue < 18.5:
print("Underweight "), print(bmivalue)
elif bmivalue >= 18.5 and bmivalue <= 24.9:
print("Healthy "), print(bmivalue)
elif bmivalue <= 25.0 and bmivalue >= 29.9:
print("Overweight "), print(bmivalue)
elif bmivalue >= 30.0:
print("Obese "), print(bmivalue)
# establish usable variables based on user input
user_weight_kg1, user_height_m1 = input("What is your weight in kilograms? "), input("What is your height in meters? ")
# convert user input to float
user_weight_kg2, user_height_m2 = float(user_weight_kg1), float(user_height_m1)
# run the function
calculatebmi(user_weight_kg2, user_height_m2)
For whatever reason, when I input "75" for the weight value and "1.7" for the height value, it simply returns:
What is your weight in kilograms? 75
What is your height in meters? 1.7
Process finished with exit code 0
If I use integers, it works fine:
What is your weight in kilograms? 80
What is your height in meters? 2
Healthy
20.0
Process finished with exit code 0
I need to be able to have my users input a string and then convert it to a float afterwards. What am I doing wrong here? I appreciate the help!
Upvotes: 1
Views: 182
Reputation: 27190
Your code contains unnecessary and repeated comparisons. It also doesn't contain any kind of validation. Try this (output modified):
def get_bmi(weight, height):
try:
if (BMI := float(weight) / (float(height) ** 2)) < 18.5:
c = 'Underweight'
elif BMI < 25.0:
c = 'Healthy'
elif BMI < 30.0:
c = 'Overweight'
else:
c = 'Obese'
return f'{BMI=:.1f} -> {c}'
except ValueError as e:
return str(e)
weight = input('Input weight in kg: ')
height = input('Input your height in metres: ')
print(get_bmi(weight, height))
Example:
Input weight in kg: 72
Input height in metres: 1.8
BMI=22.2 -> Healthy
Upvotes: 0
Reputation: 989
Try to avoid integer division at the bmivalue
calculation
bmivalue = weight / (height ** 2)
instead of
bmivalue = weight // (height ** 2)
And make sure to correct the statement at
elif bmivalue <= 25.0 and bmivalue >= 29.9:
change to
elif (bmivalue >= 25.0) and (bmivalue <= 29.9):
Upvotes: 2