You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python while循环内卡路里数值累加功能实现求助

问题修复方案

你的代码核心问题是**count_calories在每次循环的try块内被重置为0**,导致无法实现累加;同时缺少存储历史记录的结构,且循环逻辑存在无限循环的隐患。以下是修改后的完整代码:

# 初始化总卡路里计数器和历史记录列表
total_calories = 0
meal_history = []

# 初始引导输入
user_choice = input('Type "add" to add a meal, or "quit" to exit: ')

while user_choice.lower() == 'add':
    calorie_input = input('Enter the number of calories in the meal: ')
    try:
        calories = int(calorie_input)
        # 累加总卡路里
        total_calories += calories
        # 将当前餐的卡路里存入历史记录
        meal_history.append(calories)
        print(f"Added {calories} calories. Total so far: {total_calories}")
    except ValueError:
        # 仅捕获输入无法转为整数的异常,避免误处理其他错误
        print('Invalid input (must be a number). Exiting...')
        break
    # 循环末尾询问是否继续添加
    user_choice = input('Type "add" to add another meal, or "quit" to exit: ')

# 退出后展示总结信息
print("\n--- Daily Calorie Summary ---")
print(f"Total calories consumed: {total_calories}")
print(f"Meal calorie history: {meal_history}")

关键修改说明

  • 变量初始化位置调整:将total_calories和meal_history移到循环外部,确保每次循环不会重置累加值和历史记录。
  • 优化循环逻辑:每次循环结束后重新询问用户选择,解决原代码一旦进入循环就无限运行的问题;用lower()统一处理输入大小写,无需单独判断add/Add。
  • 添加历史记录功能:用列表meal_history存储每一次输入的卡路里数值,方便后续查看。
  • 精准异常捕获:只捕获ValueError(输入无法转为整数的情况),避免捕获无关异常导致程序意外行为。
  • 实时反馈与总结:添加实时累加提示,退出时展示总卡路里和历史记录,提升用户体验。

内容的提问来源于stack exchange,提问作者Tommy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:50:38