我正在編寫一個腳本,提示用戶輸入狀態名稱。腳本檢查狀態是否真的在字典中,並返回資本。如果國家不在詞典中,則表明它不在詞典中。我嘗試除了KeyError,但Python仍然給我一個錯誤。我做錯了什麼?嘗試除了錯誤異常 - KeyError
state_dictionary = {'Colorado': 'Denver', 'Alaska': 'Juneau', 'California': 'Sacramento',
'Georgia': 'Atlanta', 'Kansas': 'Topeka', 'Nebraska': 'Lincoln',
'Oregon': 'Salem', 'Texas': 'Austin', 'New York': 'Albany'}
if True:
search_state=input("What is the State of the Capital you want to know? ")
try:
state_dictionary[search_state]
except KeyError:
print ('No such a State')
print (state_dictionary[search_state])
What is the State of the Capital you want to know? Italia
No such a State
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-38-c6d25bb66225> in <module>()
13 except KeyError:
14 print ('No such a State')
---> 15 print (state_dictionary[search_state])
KeyError: 'Italia'