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>Your break is not in the if scope... so it will break on the first attempt.</p>

python for-loop dictionary exception