擅长:python、mysql、java
<p>这里不会有<code>KeyError</code>,因为您的代码永远不会厌倦访问字典,只需检查键是否在<code>keys</code>中。您可以简单地这样做来实现相同的逻辑:</p>
<pre><code>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')
</code></pre>
<p>样本运行:</p>
^{pr2}$
<p>{cd3>如果你只需要检查一个键</p>