0

I'm a complete beginner in Python so please forgive me. I need help with my Try/Except handling in my code below. If the user doesn't enter a number for height or inches, I want it to continue prompting for height/inches. My code seems to start over with prompting for the name. What am I doing wrong?

#Intro to BMI Calculator
print("Welcome to my BMI calculator!")
print("Give me your height and weight, I'll calculate your Body Mass Index")

#Create an empty dictionary to gather names, height, weight, and BMI (Will use later once code is complete)
#bmi_data = []

# Gather BMI metrics from user
def bmi_metrics(): 
    while True:
        try:
            name = (input("\nWhat's your name?  "))
            height = float(input(f"\nHi {name.title()}, please enter your height in inches: "))
            weight = float(input("Please enter your weight in pounds: "))
            BMI = (weight  * 703) / (height ** 2)
            
            print(f"{name.title()}, your BMI is {BMI:.2f}")
            if BMI <= 18.5:
                print(f"A person with a BMI of {BMI:.2f} is underwieght ")
            elif BMI <= 24.9:
                print(f"A person with a BMI of {BMI:.2f} is normal weight ")
            elif BMI <= 29.9:
                print(f"A person with a BMI of {BMI:.2f} is overweight ")
            else:
                print(f"A person with a BMI of {BMI:.2f} is obese")

            return BMI
        
        except ValueError: # If not a number, prompt again
            print("Oops that doesn't look like a number, try again.")

#Prompt user to run calculator again       
def prompt_again(): 
    while True:
        run_again = input("\nWould you like to do another calculation (y/n)? ")
        if run_again == 'y':
            bmi_metrics()
        elif run_again == 'Y':
            bmi_metrics()
        elif run_again == 'N':
            break
        elif run_again == 'n':
            break
        else:
            print("Please enter 'y' or 'n' ")

    print("Thanks for playing!")
    
bmi_metrics()
prompt_again()

Also please let me know if you would clean up the code in any way.. All feedback is welcome!

Yuddy
  • 15
  • 3
  • Nothing's wrong. If you don't want the name query repeated, then move it outside of the `while True:` loop. – Tim Roberts Feb 08 '22 at 18:33
  • Put a loop with `try/except` around each input, not around the whole calculation. – Barmar Feb 08 '22 at 18:36
  • This question should not have been closed. The issue here is NOT a failure to understand how to repeat the query, it's how NOT to repeat the whole query. – Tim Roberts Feb 08 '22 at 18:39
  • Oh wow... Can't believe it was something that simple. Thanks for your help. – Yuddy Feb 08 '22 at 20:14

0 Answers0