所以,我有一本字典,上面有国家名称和相应的股票指数。用户被要求输入五个不同的国家,程序会获取五个相应的股票指数并对数据进行处理。在
当被要求输入时,我对照字典检查是否能找到这个国家,这种情况发生了五次。现在,处理异常的部分并不是我希望的那样。我的循环和/或异常处理有什么问题??在
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
,因为您的代码永远不会厌倦访问字典,只需检查键是否在keys
中。您可以简单地这样做来实现相同的逻辑:样本运行:
^{pr2}${cd3>如果你只需要检查一个键
从doc
在您的代码段中,如果您想在用户插入一个不在国家dict中的键时打印一条消息,您可以简单地添加else语句而不是catch exception。在
您可以通过以下方式更改代码:
你的休息不在if范围内。。。所以第一次尝试它就会破裂。在
相关问题 更多 >
编程相关推荐