【问题标题】:How do you add user counter to BMI calculator?如何将用户计数器添加到 BMI 计算器?
【发布时间】:2021-12-25 18:34:42
【问题描述】:

我已经制作了这个 BMI 计算器,并且我希望用户每次使用 BMI 计算器时输入“y”来计算底部的用户计数。我似乎无法让代码工作。有什么帮助吗?


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

【问题讨论】:

  • 您只在用户退出程序时递增计数器 (user_continue != "y")。这意味着它永远不会是 1 以外的任何东西。为什么不在循环顶部增加计数并在循环后打印消息。

标签: python for-loop counter


【解决方案1】:

您想在循环的任何迭代中增加计数器,因此您需要在循环内增加 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

【讨论】:

  • 我该怎么做?这是我第一次使用堆栈溢出 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多