我正在制作一个常量营养素计算器。如果用户创建错误计算器,则此计算器只需重新启动并返回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.
是否有不同的方法来解决这个问题,以防止这种情况发生?
答案 0 :(得分: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
答案 1 :(得分: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()
你再次打电话给主。