我正在为我的个人理财项目工作,我试图让用户能够选择他们希望交易的货币。我试图进行错误处理,如果他们输入的键在字典中不存在,它会显示一条消息并关闭程序。但现在,即使我输入了正确的键,它仍然会关闭
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语句,它可以工作,但不符合预期,我可以键入任何单词,它不必是键,它会将它分配给变量,甚至不检查它是否作为键存在于字典中
您不希望在检查第一个键后立即跳出。一个解决办法可能是
当然,更好的方法是检查键是否在字典中:
您正在检查字典中的每个键是否都已输入,这是不可能的。您可以通过在
if
子句末尾添加break
语句轻松解决此问题:在任何情况下,此代码都不是很pythonic,您可以用整个循环替换此代码,如果dict中没有键,则将返回None:
如果要检查给定词典中是否存在
key
,可以执行此操作key in dict
或者您可以使用
.get()
相关问题 更多 >
编程相关推荐