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

点餐程序开发:用户输入选择字典键时遇TypeError问题求助

解决点餐程序中的TypeError错误

错误原因分析

  • menu.update是字典的内置方法,你用menu.update[key]试图通过下标访问它,这是核心错误——方法对象不支持下标操作,这就是你看到'builtin_function_or_method' object is not subscriptable报错的原因。
  • 你给quan的赋值用了逗号,导致quan变成了元组而非单独的数量值,逻辑完全错误。
  • 代码里的if语句缩进错误,且continue必须在循环(如while)内部使用,否则会触发语法错误。

修正后的代码

menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99"},
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}

isOrdering = True
while isOrdering:
    try:
        key = int(input("Please select your item:\n"))
        if key < 1 or key > 6:
            print("Invalid selection. Please try again.\n")
            continue
        quan = int(input("Enter quantity: \n"))
        # 直接给对应菜品字典添加quantity键值对
        menu[key]["quantity"] = quan
        print(f"已更新菜品 {menu[key]['item']} 的数量为 {quan}")
        # 可选:添加继续点餐的交互
        continue_order = input("是否继续点餐?(y/n): ").lower()
        if continue_order != 'y':
            isOrdering = False
    except ValueError:
        print("输入无效,请输入数字。\n")

# 验证更新结果
print("\n更新后的菜单:")
for k, v in menu.items():
    print(f"{k}: {v}")

关键修正点

  1. 用while循环包裹点餐逻辑,解决continue的合法使用问题,同时支持重复点餐。
  2. 去掉错误的menu.update[key]写法,直接通过menu[key]["quantity"] = quan修改嵌套字典,这是给菜品添加数量字段的正确方式。
  3. 修复quan的赋值逻辑,去掉逗号,让它正确接收输入的整数数量。
  4. 添加try-except捕获非数字输入的情况,提升程序健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:45:53