0

I am trying to code a BMI calculator. I am trying to make sure the user input to be a float only, so I used except, but I couldn't make it loop the check.

def error_handeling():
    try:
        weight = float(input("enter your weight in KG : "))
    except ValueError:
        weight = float(input("enter your REAL weight in KG : "))

for i in range(100):
    error_handeling()

while weight < 2.0:
    print("enter a valid weight")
    weight = float(input("enter your weight in KG : "))
    if False:
        break


height = float(input("enter your height in Meters: "))


while height < 0.5 or height > 2.2:
    print("enter a valid height ")
    height = float(input("enter your height in meters : "))
    if False:
        break


BMI = weight / (height**2.0)

print("your bmi is : " + str(BMI))

if BMI < 18.5:
    print("you're underweight EAT MORE !!")
if BMI > 18.5:
    print("you're overweight EAT LESS + practise sport !!")
if BMI == 18.5:
    print("you're in perfect weight")
  • @not_speshal i am trying to force the user to enter a float number , or an integer number then it will be automatically converted to float , i don't want the user to enter a word instead of a number – kimanxo 313 Oct 25 '21 at 14:45

1 Answers1

1

Replace your error_handling function with this:

def get_weight():
    while True:
        try:
            weight = float(input("enter your weight in KG : "))
            return weight
        except ValueError:
            print("please enter a valid number.")

and call get_weight when you need the user's weight.

That way it will ask for the weight over and over again until the user provides a good answer.