Home > Back-end >  How do you add user counter to BMI calculator?
How do you add user counter to BMI calculator?

Time:11-14

I've made this BMI calculator and I want the user count at the bottom to count every time the user has used the BMI calculator by entering "y". I can't seem to get the code to work. Any help?


user_continue = "y"
counter = 0

while user_continue == "y":
    weight = float(input("What is your weight? (KG) "))
    height = float(input("What is your height? (Metres) "))

#formula to convert weight and height to users bmi 
    bmi = weight/(height*height)

    print("Your BMI is", bmi)

#indicators to state if user is either underwieght, overweight or normal
    
    if bmi < 18:
        print("It indicates you underweight.")
    elif bmi >= 18 and bmi < 25:
        print("It indicates you are within normal bounds.")
    elif bmi >= 25:
        print("It indicates you are overweight.")

    user_continue = input("Add Another BMI? y/n: ")

# add counter
    
    if user_continue != "y":
        counter =1

        print(counter)
        print("\t\tThank You for using BMI calculator by Joe Saju!")
        print("\n\t\t\t\tPress ENTER to Exit.")
        break

CodePudding user response:

You want to increase the counter in any iteration of the loop so you need increase the counter variable inside the loop but not in the ending if statement.

Tip: increase counter variable at the begining of the loop(like in the code below)

In your case the counter increase only if the user want exit. so it will counter only one time.

user_continue = "y"
counter = 0

while user_continue == "y":
    # increase the counter at the begining
    counter =1
    weight = float(input("What is your weight? (KG) "))
    height = float(input("What is your height? (Metres) "))

#formula to convert weight and height to users bmi 
    bmi = weight/(height*height)

    print("Your BMI is", bmi)

#indicators to state if user is either underwieght, overweight or normal
    
    if bmi < 18:
        print("It indicates you underweight.")
    elif bmi >= 18 and bmi < 25:
        print("It indicates you are within normal bounds.")
    elif bmi >= 25:
        print("It indicates you are overweight.")

    user_continue = input("Add Another BMI? y/n: ")
    
    if user_continue != "y":
        # counter =1 line removed and moved to the begining

        print(counter)
        print("\t\tThank You for using BMI calculator by Joe Saju!")
        print("\n\t\t\t\tPress ENTER to Exit.")
        break
  • Related