How can I specify which try block to continue from?

I have the following code

while True:
                        try:
                            height_input=input(f"Please enter your height in meters : ")
                            height=float(height_input)
                            # weight_input=input(f"Please enter your weight in kilograms")
                           
                        except ValueError:
                            print("Invalid Input. Please Try Again")
                            continue
                        try:
                            weight_input=input(f"Please enter your weight in kilograms")
                            weight=float(weight_input)
                        except ValueError:
                            print("Invalid Input. Please Try Again")
                            continue
                                                                       
                        try:
                            bmi=weight/(height*height)
                            print(round(bmi,2))
                        finally:
                            break

If I encounter an error with an invalid format for the line related to the user entering weight, it asks me for the height again even though that might have been entered correctly and was part of the first try block

How do I specify that if an error is encountered in the second try block, to ask the user to input the weight again (which was part of the second try block) and not return to the user input question from the first try block? (the height)

For example the current result:

Question: Please Enter height

User Input: 2

Question: Please Enter Weight:

User Input: ghsdek

Error Message: "Invalid Input. Please Try Again"

Question: Please Enter height

Expected result:

Question: Please Enter height

User Input: 2

Question: Please Enter Weight:

User Input: ghsdek

Error Message: "Invalid Input. Please Try Again"

Question: Please Enter Weight

>Solution :

You can split the code to multiply while codes, also you need to check for height being different to 0 like below:

while True:
    try:
        height_input = input("Please enter your height in meters : ")
        height = float(height_input)
        if height != 0:
            break

    except Exception:
        print("Invalid Input. Please Try Again")

while True:
    try:
        weight_input = input("Please enter your weight in kilograms")
        weight = float(weight_input)

        break
    except Exception:
        print("Invalid Input. Please Try Again")

bmi = weight/(height*height)
print(f"Your bmi is: {round(bmi,2)}")

Leave a Reply