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

Python三明治点餐程序问题:获取用户所选食材对应价格并求和

问题解决:提取所选食材的单个价格并计算总价

你的问题出在这两行代码:

selectedMenu.append(prices['teaType'].values()) 
selectedMenu.append(prices['milkType'].values())

values()方法会返回对应类别下所有食材的价格集合,而不是你选中的那一个食材的价格。要获取用户所选食材的单价,直接用用户选择的食材名称作为键,从对应类别字典中取值即可。

修改后的完整代码如下:

import pyinputplus as pyip

prices = {'teaType': {'coffee': 7, 'lipton': 5.5, 'toptea': 5, 'bournvita': 6, 'milo': 6.5},
'milkType': {'peak': 11, 'three_crowns': 9.2, 'cowbell':8.7, 'coolcow': 8},
'breadType': {'wheat_bread': 22, 'white_bread': 15, 'coconut_bread': 17, 'sourdough': 20, 'buttered_bread': 18},
'proteinType':{'chicken': 12, 'turkey': 10.5, 'beef': 9.3, 'ham': 13, 'tofu': 8.7},
'cheeseType': {'swiss': 4, 'shawarma': 5, 'mozerrella': 4.3, 'cheddar':3.8},
'butterType': {'mayo': 2.6, 'mustard': 2.4, 'lettuce': 3, 'tomato': 5}}

selectedMenu = []

# 选择茶类并添加对应价格
tea = pyip.inputMenu(['coffee', 'lipton', 'toptea', 'bournvita', 'milo'],
      prompt='Type a number for the tea you want.\n', numbered=True)
selectedMenu.append(prices['teaType'][tea]) 

# 选择奶类并添加对应价格
milk = pyip.inputMenu(['peak', 'three_crowns', 'cowbell', 'coolcow'],
     prompt='Select the milk you want with it\n', numbered=True)
selectedMenu.append(prices['milkType'][milk])

# 计算并打印总价
total_price = sum(selectedMenu)
print(f"Selected items prices: {selectedMenu}")
print(f"Total price: {total_price}")

关键改动说明:

  • 把prices['teaType'].values()改为prices['teaType'][tea]:tea是用户选择的食材名称(字典的键),直接通过键获取对应的值(单价)
  • 同理修改奶类的价格获取逻辑
  • 添加总价计算:用sum(selectedMenu)对列表中的所有单价求和,得到最终总价

另外,inputMenu的选项均来自对应类别的字典键,用户无法输入不在键集合内的值,因此可以去掉多余的if判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:15:24