Skip to main content
 首页 » 编程设计

python之如何使用 while 循环将值累加起来

2025年05月04日8cloudgamer

我正在编写一个简单的 Python 程序,帮助用户跟踪他们消耗的卡路里数量,并显示用户是否超过或在他们当天的卡路里目标内。

到目前为止,这是我的代码。

caloriesGoal = float(input('Enter the calorie goal for number of calories for today: ')) 
 
numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today')) 
totalConsumed = 0 
while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000): 
      numberOfCaloriesConsumed = float(input('How many calories did you consumed?')) 
      totalConsumed += numberOfCaloriesConsumed 
      count = count + 1 
print('Your total calories consumed is: ' , totalConsumed) 
 
if(caloriesGoal > totalConsumed): 
      print('The user is within their goal by ', (caloriesGoal - totalConsumed)) 
else: 
      print('The user exceeded their goal by', (totalConsumed - caloriesGoal)) 

请您参考如下方法:

试一试,对于您预期输入的内容,输出会更加清晰。

while True: 
    caloriesGoal = float(input('Enter the calorie goal the day: ')) 
    if 1500 <= caloriesGoal <= 3000: 
        break 
    else: 
        print("Error: Goal must be between 1500 and 3000 calories!") 
 
totalConsumed = 0 
items = 0 
 
while True: 
      caloriesConsumed = float(input('Item {}: How many calories was it? (-1 to stop)'.format(items+1))) 
 
      if caloriesConsumed < 0: 
          print("Input stopped") 
          break 
 
      totalConsumed += caloriesConsumed  
      items += 1 
 
      if totalConsumed > caloriesGoal: 
          print("Goal reached/exceeded!") 
          break 
 
print('You consumed {} calories in {} items.'.format(totalConsumed, items)) 
 
if caloriesGoal > totalConsumed: 
      print('The user is within their goal by ', (caloriesGoal - totalConsumed)) 
else: 
      print('The user exceeded their goal by', (totalConsumed - caloriesGoal))