You need to enable JavaScript to run this app. Python用字典开发货币转换器时触发‘builtin_function_or_method’不可下标错误
优惠活动
大模型
产品
解决方案
定价
更多

Python用字典开发货币转换器时触发‘builtin_function_or_method’不可下标错误

报错含义

'builtin_function_or_method' is not subscriptable的核心逻辑是:你用方括号下标[]的方式去访问了一个内置的函数/方法对象,这类对象本身不支持下标索引操作,因此触发报错。
放到你的代码场景里,condict.values、condict.key这类写法拿到的不是字典存储的内容,而是方法本身的定义,你直接对方法加下标取元素,从调用逻辑上就是错的。

代码存在的具体问题
  • 遗漏方法调用的括号:字典的values()、keys()是内置方法,必须加括号执行后才会返回可遍历的键/值集合,不写括号拿到的是方法对象本身,自然不能用下标取值;
  • 误用无效属性:你代码里写的condict.key根本不存在,Python字典没有名为key的内置属性,对应取所有键的方法是keys();
  • 取值逻辑稳定性差:就算你正确加括号调用了values(),返回的字典视图对象也不支持直接数字下标访问,必须转成列表才能索引,且这种写法完全依赖字典的插入顺序,一旦字典内容顺序调整,所有货币和序号的对应关系就会错乱。
修复方案

不要强行从字典的键值视图里按下标取内容,最稳妥的方式是把用户输入的选项序号和对应货币名称做一一绑定的有序列表,索引值和用户输入的序号偏移量(序号-1)严格对应,再通过货币名直接查字典拿汇率,参考可运行代码:

def Currency():
  # 按用户给的选项顺序排列货币名,下标和序号-1完全对应
  currency_order = ["USD", "Euro", "Yen", "UK Pound", "Swiss Franc"]
  condict = {
    "USD": 1,
    "Euro": 1.21,
    "Yen": 0.0094,
    "UK Pound": 1.39,
    "Swiss Franc": 1.12,
  }
  UserOrigin = int(input("Write the number to indicate which is the original currency.\n1. US. Dollars\n2. Euro\n3. Yen\n4. UK Pound\n5. Swiss Franc\n"))
  UserResult = int(input("Write the number to indicate which is the currency to convert to.\n1.US. Dollars\n2. Euro\n3. Yen\n4. UK Pound\n5. Swiss Franc\n"))
  UserAmount = int(input("Enter the amount:\n"))
  # 根据序号取对应货币名,直接从字典查汇率
  origin_name = currency_order[UserOrigin - 1]
  target_name = currency_order[UserResult - 1]
  # 转换逻辑:先折算成等值美元,再换算为目标货币
  usd_value = UserAmount * condict[origin_name]
  final_value = usd_value / condict[target_name]
  print("{} {}s are {} {}s".format(UserAmount, origin_name, final_value, target_name))

Currency()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 08:36:07