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

Python字典键值条件匹配后无法正常打印SIM信息求助

修复你的SIM选项打印问题

我来帮你搞定这个问题,你的代码里有两个关键bug导致选择手机后无法正常展示SIM选项,咱们一步步拆解修复:

1. 错误的设备类型判断逻辑

你现在用str(device[device_choice]) == 'Phone'来判断是不是手机,但device[device_choice]是一个列表对象(比如选中BPCM的话,它的值是['Phone', 'Description: Compact', 'price', 29.99]),把整个列表转成字符串后肯定不等于单纯的'Phone'。

正确的做法是直接取列表的第一个元素来判断设备类型:

if device[device_choice][0] == 'Phone':

2. 未定义的keys变量导致报错

你写的print("\nSIMS available: " + str(sims[keys]))里的keys完全没有定义,而且要展示所有SIM选项,应该像之前遍历设备列表那样,循环打印每个SIM的代码和详细信息,而不是试图访问一个不存在的键。

完整修正后的代码

我还顺便修复了几个小细节(比如Python 3兼容的输入方式,合并字典项的正确写法,以及增加无效输入的提示):

device = { 
    'BPCM' : ['Phone', 'Description: Compact', 'price', 29.99], 
    'BPSH' : ['Phone', 'Description: Clam Shell', 'price', 49.99], 
    'RTMS' : ['Tablet', 'Description: RoboTab - 10-inch screen and 64GB memory', 'price', 299.99], 
    'RTLM' : ['Tablet', 'Description: RoboTab - 10-inch screen and 256 GB memory', 'price', 499.99], 
}
sims = { 
    "SMNO" : ['SIM card', 'Description: SIM Free (no SIM card purchased)', 'price', 0.00], 
    "SMPG" : ['SIM card', 'Description: Pay As You Go (SIM card purchased)', 'price', 9.99], 
}

print("Hello customer, here is your list of phone, tablet and SIM choices. Please choose a phone or tablet by entering your name and the item code:")
# Python 3中合并字典items需要转成列表后相加
for key, value in list(device.items()) + list(sims.items()):
    print("\nItem Code: " + key)
    print(" " + str(value))

name = input("\nPlease tell me your name? ")
print("Hello " + name)

device_choice = input("Please enter item code for the phone or tablet you want?: ")
if device_choice in device:
    print(f"Item Code Chosen {device_choice}: {device[device_choice]}")
    # 正确判断当前设备是手机
    if device[device_choice][0] == 'Phone':
        print("\nSIMS available:")
        # 循环打印所有SIM选项的信息
        for sim_key, sim_value in sims.items():
            print(f"\nItem Code: {sim_key}")
            print(f" {sim_value}")
        print("\nPlease tell me if you want SIM free or Pay As You Go by choosing its item code? ")
else:
    print("Oops, that's an invalid device code!")

核心修复总结

  • 用列表索引[0]获取设备类型,替代错误的列表转字符串判断
  • 遍历sims.items()来展示所有SIM选项,解决keys未定义的问题
  • 增加了无效设备代码的提示,让程序更健壮
  • 改用f-string优化了打印格式(如果你习惯旧的字符串拼接,也可以改回去)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:42:36