【发布时间】:2017-02-01 00:47:49
【问题描述】:
所以,我有一本包含国家名称和相应股票指数的字典。用户被要求输入五个不同的国家,程序获取五个相应的股票指数并对数据进行处理。
当被要求输入时,我检查字典是否可以找到该国家/地区,这种情况发生了五次。现在,处理异常的部分没有做我希望的事情。我的循环和/或异常处理有什么问题??
ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')
for i in range(0, 5):
while True:
try:
countr = input('Please enter country no. %d: ' %(i+1))
countr = countr.title()
if countr in ex_dict.keys():
print('Found the corresponding stock index! \n')
countries.append(countr)
break
except KeyError:
print('Country not found, please try again! \n')
【问题讨论】:
-
您希望它做什么,而它又做了什么?
-
你不需要捕获 KeyError,因为你不会遇到。也使用
if countr in ex_dict而不是if countr in ex_dict.keys() -
一个简单的 else 语句而不是捕获 KeyError 将解决您的问题
标签: python for-loop dictionary exception