如何使用while循环来增加值?

时间:2016-02-11 05:19:09

标签: python python-3.x

我正在编写一个简单的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))

2 个答案:

答案 0 :(得分:1)

尝试这一点,输出更清楚你想要进入的东西。

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))

答案 1 :(得分:0)

欢迎使用Python!这是我的第二语言,但我喜欢它,就像我的第一语言。你的代码中发生的事情很少有点奇怪。

有趣的是,您正在检查numberOfCaloriesConsumed。如果您正在进入Krispy Kreme甜甜圈,那么您将输入190卡路里。让我们回顾一下:

while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000):

如果我们看一下这条线......

numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today'))

...我们为Krispy Kreme甜甜圈输入190,然后我们不能进入循环。你可能想要改变的是一个带有中断机制的无限循环:

while 1:
    numberOfCaloriesConsumed = input('How many calories did you consumed?')
    if (numberOfCaloriesConsumed == "q") or (totalConsumed > 3000): # keep numberOfCaloriesConsumed as a string, to compare for the break
        if (totalConsumed < 1500):
            print("You need to eat more!\n")
        else:
            break
    else:
        if (totalConsumed + int(numberOfCaloriesConsumed)) > 3000:
            print("You eat too much! You're done now!\n")
            break
        totalConsumed = totalConsumed + int(numberOfCaloriesConsumed) #make the string an int, if we're adding it

这样,当用户手动退出循环时(或者如果他们输入的卡路里太多),将退出代码循环。现在,您的用户应该能够输入卡路里数据并将其添加到其中。

另外,我会删除计数器,因为此循环不需要计数器。我们有几个原因可以解释为什么我们不需要这个柜台:

  • 计数器不会直接影响循环(例如,没有while counter < 5
  • 我们让计算机要求用户输入,所以程序停止并控制人因此没有无限循环
  • 我们有break语句将我们从(新)循环
  • 中删除