Python 当键不在字典中时,如何使用异常处理创建for循环?
所以,我有一本字典,上面有国家名称和相应的股票指数。用户被要求输入五个不同的国家,程序获取五个相应的股票指数,并对数据进行处理 当我被要求输入时,我对照字典检查是否能找到国家,这种情况发生了五次。现在,处理异常的部分并不是我所希望的。我的循环和/或异常处理有什么问题Python 当键不在字典中时,如何使用异常处理创建for循环?,python,for-loop,dictionary,exception,Python,For Loop,Dictionary,Exception,所以,我有一本字典,上面有国家名称和相应的股票指数。用户被要求输入五个不同的国家,程序获取五个相应的股票指数,并对数据进行处理 当我被要求输入时,我对照字典检查是否能找到国家,这种情况发生了五次。现在,处理异常的部分并不是我所希望的。我的循环和/或异常处理有什么问题 ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shor
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')
您的中断不在if范围内。。。因此,它将在第一次尝试时中断。您的中断不在if范围内。。。因此,它将在第一次尝试时中断。此处不会出现
键错误
,因为您的代码访问字典时不会感到厌倦,只需检查键是否在键中。您可以简单地执行此操作以实现相同的逻辑:
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')
样本运行:
Please choose five stock exchanges to analyse,
just name the corresponding countries
Please enter country no. 1: sdf
Country not found, please try again!
Please enter country no. 1: USA
Found the corresponding stock index!
Please enter country no. 2: Aregtng
Country not found, please try again!
Please enter country no. 2: Argentina
Found the corresponding stock index!
Please enter country no. 3: United States
Found the corresponding stock index!
Please enter country no. 4: usa
Found the corresponding stock index!
Please enter country no. 5: usa
Found the corresponding stock index!
注意:.keys()
太过分了:要检查一个键是否在字典中,您只需要在某些目录中使用k这里就不会出现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')
样本运行:
Please choose five stock exchanges to analyse,
just name the corresponding countries
Please enter country no. 1: sdf
Country not found, please try again!
Please enter country no. 1: USA
Found the corresponding stock index!
Please enter country no. 2: Aregtng
Country not found, please try again!
Please enter country no. 2: Argentina
Found the corresponding stock index!
Please enter country no. 3: United States
Found the corresponding stock index!
Please enter country no. 4: usa
Found the corresponding stock index!
Please enter country no. 5: usa
Found the corresponding stock index!
注意:.keys()
太过分了:要检查某个键是否在字典中,您只需要从
每当请求dict()对象(使用格式a=adict[key]),并且该键不在字典中时,Python都会引发一个KeyError
在您的代码段中,如果您希望在用户插入countries 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')
从
每当请求dict()对象(使用格式a=adict[key]),并且该键不在字典中时,Python都会引发一个KeyError
在您的代码段中,如果您希望在用户插入countries 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 key in dict.keys()
- 而且,有很多循环。我认为
对于在(0,5)范围内的I来说就足够了。将变得不那么复杂
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):
countr = raw_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)
else:
print('Country not found, please try again! \n')
输出:
C:\Users\dinesh_pundkar\Desktop>python c.py
Please choose five stock exchanges to analyse,
just name the corresponding countries
Please enter country no. 1: USA
Found the corresponding stock index!
Please enter country no. 2: asd
Country not found, please try again!
Please enter country no. 3: asd
Country not found, please try again!
Please enter country no. 4: USA
Found the corresponding stock index!
Please enter country no. 5: United states
Found the corresponding stock index!
C:\Users\dinesh_pundkar\Desktop>
几点:
- 您的代码永远不会遇到异常,因为您正在使用
if key in dict.keys()
- 而且,有很多循环。我认为
对于在(0,5)范围内的I来说就足够了。将变得不那么复杂
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):
countr = raw_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)
else:
print('Country not found, please try again! \n')
输出:
C:\Users\dinesh_pundkar\Desktop>python c.py
Please choose five stock exchanges to analyse,
just name the corresponding countries
Please enter country no. 1: USA
Found the corresponding stock index!
Please enter country no. 2: asd
Country not found, please try again!
Please enter country no. 3: asd
Country not found, please try again!
Please enter country no. 4: USA
Found the corresponding stock index!
Please enter country no. 5: United states
Found the corresponding stock index!
C:\Users\dinesh_pundkar\Desktop>
我假设你想让它给你一个消息,如果股票不在字典里,我修改了代码做同样的事情
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 not in ex_dict.keys():
print ('Try again!')
else:
print('Found the corresponding stock index! \n')
countries.append(countr)
我假设你想让它给你一个消息,如果股票不在字典里,我修改了代码做同样的事情
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 not in ex_dict.keys():
print ('Try again!')
else:
print('Found the corresponding stock index! \n')
countries.append(countr)
你希望它能做什么,它能做什么呢?你不需要捕捉关键错误,因为你不会遇到关键错误。也可以使用if countr in ex_dict
而不是if countr in ex_dict.keys()
一个简单的else语句而不是捕获KeyError来解决您的问题您希望它做什么,它做什么呢?您不需要捕获KeyError,因为您不会遇到这样的错误。也可以使用if countr in ex_dict
而不是if countr in ex_dict.keys()
一个简单的else语句而不是捕获KeyError来解决您的问题。您是否尝试了该代码?它在有错误和无错误的情况下都能很好地循环。我的意思是,一个带中断的while循环保证会触发是没有意义的。但我承认这并没有回答你关于捕获异常的问题。。。正如其他人所说,在ex_dict.keys()中尝试countr时,代码没有引发任何键错误。
您是否尝试了该代码?它在有错误和无错误的情况下都能很好地循环。我的意思是,一个带中断的while循环保证会触发是没有意义的。但我承认这并没有回答你关于捕获异常的问题。。。正如其他人所说,在ex_dict.keys()中尝试countr时,代码没有引发任何键错误。