【问题标题】:Summing up numbers inside while function在while函数中总结数字
【发布时间】:2022-10-13 15:01:54
【问题描述】:

该程序的目标是要求用户输入给定膳食中的卡路里数量。稍后我想添加数字,以便程序记住以前的输入。这只是程序的一部分,但稍后它会返回到 user_input_calories,这样用户就可以根据需要多次输入卡路里。可能 count_calories 不应该为零。有人可以帮我解决这个问题或添加一些我可以查看的参考吗?

start=input('Type add to add a meal:')
while start=='add' or start=='Add': 
user_input_calories=input('Enter the number of calories in the meal:')
try:
    nr1=int(user_input_calories)
    count_calories=0 
    count_calories=count_calories+nr1
except:
    print('You have finised eating for the day')
continue

【问题讨论】:

  • 您需要一个循环外的求和变量(即移动 count_calories)。每次循环运行时,循环内定义的任何变量都将被“重置”。

标签: python while-loop count


【解决方案1】:

这是马特克拉克在评论中写的一个例子:

start=input('Type add to add a meal: ')
count_calories=0 # Counter outside the loop
while start.lower() == 'add':
    user_input_calories=input('Enter the number of calories in the meal (q to quit): ')
    if user_input_calories == 'q': # Added a command to end the program and count the calories
        print('You have finised eating for the day')
        print(f'You ate: {count_calories} calories')
        break
    try:
        user_input_calories = int(user_input_calories) # Try to convert to integer and add the value
        count_calories += user_input_calories
    except:
        print("You didn't enter a number")

结果:

Type add to add a meal: add
Enter the number of calories in the meal (q to quit): 100
Enter the number of calories in the meal (q to quit): 200
Enter the number of calories in the meal (q to quit): 300
Enter the number of calories in the meal (q to quit): q
You have finised eating for the day
You ate: 600 calories

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2021-11-04
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多