python - 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 语句,它可以工作但没有按预期工作,我可以键入任何单词,它不必是键,它会将它分配给变量,甚至不检查它是否作为字典中的键存在
解决方案
那应该工作:
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()
推荐阅读
- node.js - 使用最新节点时 node-sass 出错:stretch docker image
- python - 从另一个线程或进程更新 Gtk.ProgressBar
- python - 如何在 TensorFlow 中使用 Eager Execution 进行保存和恢复?
- javascript - 如何在 Java 中中止文件下载?
- azure - Azure 功能:队列触发器删除消息,但不触发
- wpf - 在功能区内的控件中正确获取图像大小
- android - RxJava2(Android):PublishSubject 只向活动发出一次?
- python - 在python循环中获取href链接和文本
- android - 事件处理在微调器和按钮的角色中扮演什么角色?
- python - Python添加密码以修改功能