擅长:python、mysql、java
<p>从<a href="https://wiki.python.org/moin/KeyError" rel="nofollow">doc</a></p>
<blockquote>
<p>Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.</p>
</blockquote>
<p>在您的代码段中,如果您想在用户插入一个不在国家dict中的键时打印一条消息,您可以简单地添加else语句而不是catch exception。在</p>
<p>您可以通过以下方式更改代码:</p>
<pre><code>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>