首页 > 解决方案 > Python循环不会正确遍历字典

问题描述

我正在研究我的个人理财计划,我试图让用户能够选择他们希望交易的货币。如果他们输入的密钥不存在,我正在尝试进行错误处理在字典中它显示一条消息并关闭程序。但是现在即使我输入了正确的键,它仍然会关闭。

print("Currency's supported: USD, EUR, CAN, YEN, GBP")
currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()


#currencySYM is a dictionary of currency ticker symbols and currency symbols
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}
#the for loop takes the input from Currencycheck and applies the correct symbol to the letters
for key in currencySYM:
    if currencyCheck == key:
        currencyCheck = currencySYM[key]

    elif currencyCheck != key:
        print("Make sure you type the correct three letter symbol.")
        exit()

如果我取出 else 语句,它可以工作但没有按预期工作,我可以键入任何单词,它不必是键,它会将它分配给变量,甚至不检查它是否作为字典中的键存在

标签: pythonpython-3.xloopsdictionaryfor-loop

解决方案


那应该工作:

currencyCheck = input("Input the currency you would like to use. Ex: 'USD' or 'EUR'...etc ").upper()

#currencySYM is a dictionary of currency ticker symbols and currency symbols
currencySYM = {'USD':'$', 'EUR':'€', 'CAN':'C$','YEN':'¥','GBP':'£'}
#the for loop takes the input from Currencycheck and applies the correct symbol to the letters
key_list = currencySYM.keys()
if currencyCheck in key_list:
    currencyCheck = currencySYM[currencyCheck]

elif currencyCheck not in key_list:
    print("Make sure you type the correct three letter symbol.")
    exit()

推荐阅读