所以,我有一個國家名稱和相應的股票指數字典。要求用戶輸入五個不同的國家,該程序將採用五個相應的股票指數,並對數據進行一些操作。如何在密鑰不在字典中時使用異常處理來創建for循環?
當被問及輸入時,我檢查字典是否可以找到國家,這會發生五次。現在,處理例外的部分並不是我所希望的。我的循環和/或異常處理有什麼問題?
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')
你希望它做什麼,它做什麼呢? –
你不需要捕捉KeyError,因爲你不會遇到一個。在ex_dict中也可以使用'如果countr in ex_dict'而不是'如果countr in ex_dict。keys()' – sisanared
簡單的else語句而不是捕獲KeyError會解決您的問題 – armak