简体   繁体   English

使用 while 循环时如何计算运行总数?

[英]How do I calculate a running total when using a while loop?

I am having a hard time wrapping my head around this code (I am very new so please be gentle), in an attempt to write a program to track calories, I can't get the code:我很难理解这段代码(我很新,所以请温柔一点),试图编写一个跟踪卡路里的程序,我无法得到代码:

caloriesPerMeal = int(input('Enter calories eaten per meal: '))

to add onto itself when it looks back and asks again if I want to enter another meal(as shown below):当它回首并再次询问我是否要输入另一餐时添加到自己上(如下图所示):

keepGoing = input('Do you want to enter another meal? (Enter yes or no) ')

The entire code I have is:我拥有的整个代码是:

keepGoing = 'yes'
totalCalories = 0
#Calories per Day
maxCaloriesPerDay = int(input('How many calories per day would you like to consume? '))
while keepGoing == 'yes':
    #Get number of calories per meal
    caloriesPerMeal = int(input('Enter calories eaten per meal: '))
    totalCalories += totalCalories + caloriesPerMeal
#See if user wants to input another meal
    keepGoing = input('Do you want to enter another meal? (Enter yes or no) ')
#Calculate calories under/over per day
if totalCalories >= maxCaloriesPerDay:
    print('You are', maxCaloriesPerDay - totalCalories, 'calories over your maximum calories per 
 day.')
elif totalCalories <= maxCaloriesPerDay:
     print('You are', maxCaloriesPerDay - totalCalories, 'calories under your maximum calories per 
day. ')

Try to do:试着做:

totalCalories = totalCalories + caloriesPerMeal

Or:或者:

totalCalories += caloriesPerMeal

Because saying that totalCalories += totalCalories + caloriesPerMeal means that totalCalories = 2*totalCalories + caloriesPerMeal因为说totalCalories += totalCalories + caloriesPerMeal意味着totalCalories = 2*totalCalories + caloriesPerMeal

keepGoing = 'yes'
totalCalories = 0
#Calories per Day
maxCaloriesPerDay = int(input('How many calories per day would you like to consume? '))
while keepGoing == 'yes':
    #Get number of calories per meal
    caloriesPerMeal = int(input('Enter calories eaten per meal: '))
    totalCalories += caloriesPerMeal
#See if user wants to input another meal
    keepGoing = input('Do you want to enter another meal? (Enter yes or no) ')
#Calculate calories under/over per day
if totalCalories >= maxCaloriesPerDay:
    print('You are', maxCaloriesPerDay - totalCalories, 'calories over your maximum calories per day.')
elif totalCalories <= maxCaloriesPerDay:
     print('You are', maxCaloriesPerDay - totalCalories, 'calories under your maximum calories per day. ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM