【发布时间】:2020-01-22 18:50:56
【问题描述】:
我正在开发我的个人理财程序,并且我正在尝试让用户能够选择他们希望交易的货币。我正在尝试在他们输入的键的位置进行错误处理在字典中不存在它会显示一条消息并关闭程序。但是现在即使我输入了正确的键,它仍然会关闭。
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 key in currencySYM: .... -
您在第一项不匹配后退出。如果根本没有匹配项,您想退出,但这里也不需要循环。
-
变量和函数名称应遵循
lower_case_with_underscores样式。另外,您使用了exit(),但我认为您可能一直在寻找break。
标签: python python-3.x loops dictionary for-loop