如何将用户计数器添加到 BMI 计算器?

How do you add user counter to BMI calculator?

我制作了这个 BMI 计算器,我希望底部的用户计数在用户每次通过输入“y”使用 BMI 计算器时进行计数。我似乎无法让代码工作。有帮助吗?


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

您想在循环的任何迭代中增加计数器,因此您需要在循环内而不是在结束 if 语句中增加 counter 变量。

提示:在循环开始时增加计数器变量(如下面的代码)

在您的情况下,只有当用户想要退出时,计数器才会增加。所以它只会反击一次。

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