为什么我的字典中只打印第一个值

Why is only the first value in my dictionary printing

给定以下代码 - 2 个字典和 for 循环。

如果我取消缩进 sim_choice = raw_input("\nPlease enter item code for the SIM card you want?: ") 行,它上面的 print 语句 print(" " + str(value)) 会打印 sims 字典中的所有值,但 else 语句将变为无效。当前输出仅打印 sims 中的第一个值?示例:

Please tell me your name? X
Hello X
Please enter item code for the phone or tablet you want?: BPCM
Item Code Chosen BPCM['Phone', 'Description: Compact', 'price', 29.99]
As you chose a phone, would you like a SIM free or Pay As You Go for - ['Phone', 'Description: Compact', 'price', 29.99]

Item Code: SMNO
 ['SIM card', 'Description: SIM Free (no SIM card purchased)', 'price', 0.0]

Please enter item code for the SIM card you want?:

我不明白为什么它不会在当前状态下打印 sims 字典中的所有值?

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 phones or tablets. Please choose a phone or tablet by entering your name and the item code:")  
for key, value in device.items(): 
    print("\nItem Code: " + key)
    print(" " + str(value)) 
name = raw_input("\nPlease tell me your name? ") 
print("Hello " + name)
device_choice = raw_input("Please enter item code for the phone or tablet you want?: ") 

if device_choice in device.keys():
    print("Item Code Chosen " + device_choice + str(device[device_choice])) 
sim_cards = ['BPCM', 'BPSH']
if device_choice in sim_cards:
    print("\nAs you chose a phone, would you like a SIM free or Pay As You Go for - " + str(device[device_choice])) 
    for key, value in sims.items():
        print("\nItem Code: " + key)
        print(" " + str(value)) 
        sim_choice = raw_input("\nPlease enter item code for the SIM card you want?: ") 
    else: 
        print("Item Code Chosen " + device_choice + str(device[device_choice]))

这是因为 raw_input 是一个阻塞语句,这意味着它将在那里停止您的代码,直到发生事件(在本例中为用户输入)。

要解决您的 else 语句的问题,您应该取消缩进以使其与对应的 if 对齐。

我认为您只需删除最后 3 行的缩进即可

if device_choice in sim_cards:
    print("\nAs you chose a phone, would you like a SIM free or Pay As You Go for - " + str(device[device_choice])) 
    for key, value in sims.items():
        print("\nItem Code: " + key)
        print(" " + str(value)) 
    sim_choice = raw_input("\nPlease enter item code for the SIM card you want?: ") 
else: 
    print("Item Code Chosen " + device_choice + str(device[device_choice]))