How to make a for loop with exception handling when key not in dictionary?
<p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>

<p>When asked for input I check against the dictionary if the country can be found, this happens five times. Now, the part where the exception is handled is not doing what I hoped. What is wrong with my loop and/or exception handling??</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:
        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')
</code></pre>

<p>There will be no <code>KeyError</code> here because your code never tires to access the dictionary, just checks if the key is in <code>keys</code>. You could simply do this to achieve the same logic:</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>Sample run:</p>

<pre><code>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! 
</code></pre>

<p>Note: <code>.keys()</code> is overkill: to check if a key is in a dictionary you only need <code>k in some_dict</code></p>

python for-loop dictionary exception