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

如何将输入作为字典键调取对应值?收银项目代码求助

收银场景项目的字典取值问题解决方法

你的代码里有三个关键问题,不用复杂函数,修正现有代码就能解决:

  1. 字典定义错误:你写的{"Chips", 1}是集合(set),不是字典(dict)。字典的键值对需要用冒号分隔,正确写法是:

    my_dictionary = {"Chips": 1}
    
  2. 代码块缩进错误:Python要求if、else下面的代码块必须缩进(通常用4个空格),否则会触发语法报错。

  3. 取值键名错误:最后一行你用字符串"order"作为键去取值,而不是用户输入的变量order,应该直接使用变量名来匹配字典中的键。

修正后的完整代码:

my_dictionary = {"Chips": 1}

# Taking order
order = input("What do you want? \n")

# Recalling order
if order in my_dictionary:
    print(f"Okay you want {order}")
else:
    print("We dont have that please leave")
    exit()

# Giving price
print(my_dictionary[order])

内容的提问来源于stack exchange,提问作者The Fearsome Asian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:27:18