0

我正在制作一个宏量营养素计算器。如果用户出错,这个计算器只会重新启动并返回到 main()。但是,我相信我在代码中使用 main() 会导致显示 2 次代码运行

这是我的代码的链接:http: //pastebin.com/FMqf2aRS

    *******Welcome to the MACRONUTRIENT CALCULATOR********
    Enter your calorie deficit: 30
    Percentage of Protein: 30
    Percent of Carbohydrates: 40
    Percentage of Fats: 40
    Total percentages surpassed 100! Please reenter percentages.
    *******Welcome to the MACRONUTRIENT CALCULATOR********
    Enter your calorie deficit: 2200
    Percentage of Protein: 30
    Percent of Carbohydrates: 30
    Percentage of Fats: 40
    You must eat 660.0 calories of protein which is equivalent to 165.0 grams of protein.
    You must eat 880.0 calories of fat which is equivalent to 97.7777777778 grams of fat.
    You must eat 660.0 calories of carbohydrates which is equivalent to 73.3333333333 grams of carbohydrates.
    You must eat 9.0 calories of protein which is equivalent to 2.25 grams of protein.
    You must eat 12.0 calories of fat which is equivalent to 1.33333333333 grams of fat.
    You must eat 12.0 calories of carbohydrates which is equivalent to 1.33333333333 grams of carbohydrates.

有没有不同的方法来防止这种情况发生?

4

2 回答 2

2

调用main()你正在做的方式是解决这个问题的错误方法。您将越来越多main()的调用推入堆栈 - 如果您连续多次输入无效条目,最终程序将崩溃。您应该使用while如下所示的循环

def main():
  while True:
      print "*******Welcome to the MACRONUTRIENT CALCULATOR********"
      calorie_deficit = float(input("Enter your calorie deficit: "))
      Percent_protein = float(input("Percentage of Protein: "))
      Percent_carb = float(input("Percent of Carbohydrates: "))
      Percent_fat = float(input("Percentage of Fats: "))
      Macro_dict = {'Protein': Percent_protein, 'Carbohydrate': Percent_carb, 'Fats': Percent_fat}
      Macro_sum = Percent_protein + Percent_carb + Percent_fat
      if not Total_Macro_Check(Macro_sum):
          continue
      Macro_percentage_to_calorie(calorie_deficit, Percent_protein, Percent_carb, Percent_fat)


def Total_Macro_Check(total_val):
  if total_val > 100:
    print "Total percentages surpassed 100! Please reenter percentages."
    return False
  if total_val < 100:
    print "Total precentages is less than 100! Please reenter precentages."
    return False
  return True
于 2013-05-31T04:59:57.653 回答
1

该代码正在执行您告诉它执行的操作:

def Total_Macro_Check(total_val):
  if total_val > 100:
    print "Total percentages surpassed 100! Please reenter percentages."
    main()
  if total_val < 100:
    print "Total precentages is less than 100! Please reenter precentages."
    main()

你再次调用main。

于 2013-05-31T04:58:47.980 回答