当键不在字典中时,如何使for循环具有异常处理功能?

2024-04-29 01:47:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有一本字典,上面有国家名称和相应的股票指数。用户被要求输入五个不同的国家,程序会获取五个相应的股票指数并对数据进行处理。在

当被要求输入时,我对照字典检查是否能找到这个国家,这种情况发生了五次。现在,处理异常的部分并不是我希望的那样。我的循环和/或异常处理有什么问题??在

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')

Tags: the字典stock国家countriesdictexunited
3条回答

这里不会有KeyError,因为您的代码永远不会厌倦访问字典,只需检查键是否在keys中。您可以简单地这样做来实现相同的逻辑:

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:
        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
        else:
            print('Country not found, please try again! \n') 

样本运行:

^{pr2}$

{cd3>如果你只需要检查一个键

doc

Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.

在您的代码段中,如果您想在用户插入一个不在国家dict中的键时打印一条消息,您可以简单地添加else语句而不是catch exception。在

您可以通过以下方式更改代码:

if countr in ex_dict.keys():
     print('Found the corresponding stock index! \n')
     countries.append(countr)
     break
else:
    print('Country not found, please try again! \n')

你的休息不在if范围内。。。所以第一次尝试它就会破裂。在

相关问题 更多 >