首页 > 解决方案 > 如何将用户计数器添加到 BMI 计算器?

问题描述

我已经制作了这个 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

标签: pythonfor-loopcounter

解决方案


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

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

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

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

推荐阅读