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

如何为饮品赋值并实现个性化年度卡路里计算?

问题分析

你的代码存在三个核心问题导致结果不随饮品变化:

  • 未为不同饮品定义对应的每罐卡路里数值,所有计算都用固定的41(该数值也不符合实际饮品的卡路里含量)
  • 输入逻辑重复:同时询问每日和每周饮用量,计算时混用导致逻辑混乱
  • 错误覆盖变量:把input内置函数和计算式拼接,直接覆盖了用户选择的饮品名称,完全忽略了用户的选择
解决方案

1. 定义饮品卡路里映射

用字典存储每种饮品的每罐标准卡路里值(以常见的12盎司罐装为例,数值参考实际营养成分):

drink_calories = {
    "Pepsi": 150,
    "Wild Cherry Coke": 150,
    "Orange Fanta": 160,
    "Mountain Dew": 170,
    "Mello Yello": 160,
    "Sprite": 140
}

2. 修正输入逻辑

选择单一统计维度避免重复输入(比如统一用每周饮用量),若需要支持多维度,可后续增加转换逻辑。这里先简化为每周饮用量计算年度总量:

cans_per_week = int(input("How many cans do you drink per week?\n"))

3. 匹配饮品并计算总卡路里

先验证用户输入的饮品是否在预设列表中,再取出对应卡路里值计算年度总量(按一年52周计算):
公式:每罐卡路里 × 每周饮用量 × 52周

完整修改后的代码

# 定义每种饮品的每罐卡路里(12盎司罐装)
drink_calories = {
    "Pepsi": 150,
    "Wild Cherry Coke": 150,
    "Orange Fanta": 160,
    "Mountain Dew": 170,
    "Mello Yello": 160,
    "Sprite": 140
}

# 获取用户输入
cans_per_week = int(input("How many cans do you drink per week?\n"))
drink_of_choice = input(f"What's your drink of choice?\n\n{chr(10).join(drink_calories.keys())}\n\n")

# 验证饮品有效性并计算年度卡路里
if drink_of_choice in drink_calories:
    calories_per_can = drink_calories[drink_of_choice]
    annual_calories = calories_per_can * cans_per_week * 52
    print(f"Your annual {drink_of_choice} calorie intake is: {annual_calories} calories")
else:
    print("Sorry, that drink is not in our list.")
额外说明
  • 若需要支持每日饮用量计算,可将公式改为calories_per_can * cans_per_day * 365,同时移除每周饮用量的输入逻辑
  • 你原代码中的41 * ... /453.592属于错误的单位转换逻辑,若有特定的单位换算需求,可明确后再调整公式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:27:24