2017-07-18 89 views
1

我正在編寫一個腳本,提示用戶輸入狀態名稱。腳本檢查狀態是否真的在字典中,並返回資本。如果國家不在詞典中,則表明它不在詞典中。我嘗試除了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' 

回答

1

你確實努力實現try,但因爲你當時還撥打電話到state_dictionary[search_state]在你的打印語句,它仍然出現了錯誤。

嘗試:

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] 
     print (state_dictionary[search_state]) 
    except KeyError: 
     print ('No such a State') 
1

錯誤實際上是快到了,在你的代碼的末尾,你這樣做是:

print (state_dictionary[search_state]) 

所以,你您的異常,然後繼續你的代碼,仍然試圖訪問不存在的state

在您嘗試訪問state_dictionary後,只需將打印件放入您的嘗試中即可。它只會在有效時纔會到達那裏。此外,請勿撥打電話兩次。存儲您的結果變量,然後打印出結果:

try: 
    capital = state_dictionary[search_state] 
    print (capital) 
except KeyError: 
    print ('No such a State') 

此外,你可以看看這個法子。您可以使用關鍵字in,以檢查是否存在於字典的條目:

search_state=input("What is the State of the Capital you want to know? ") 
if search_state in state_dictionary: 
    print (state_dictionary[search_state]) 
else: 
    print ('No such a State {}'.format(search_state)) 

一個改進的領域你也可以做,就是你現在期待確切外殼相匹配。我建議你將字典中的條目更改爲全部小寫,當你得到你的輸入時,強制檢查也是lowercase,所以如果你輸入「texas」,你將會正確匹配它。現在,如果你輸入「德克薩斯」,它將不匹配「德克薩斯州」。

所以,現在可以做(注意呼籲search_state.lower()):

state_dictionary = {'colorado': 'Denver', 'alaska': 'Juneau', 'california': 'Sacramento', 
         'georgia': 'Atlanta', 'Kansas': 'Topeka', 'nebraska': 'Lincoln', 
         'oregon': 'Salem', 'texas': 'Austin', 'new york': 'Albany'} 

try: 
    capital = state_dictionary[search_state.lower()] 
    print (capital) 
except KeyError: 
    print ('No such a State') 
0

添加一個「別人的語句,除了嘗試。如果沒有例外,它只會執行:

try: 
    state_dictionary[search_state] 
except KeyError: 
    print ('No such a State') 
else: 
    print (state_dictionary[search_state]) 
0

你有一本字典,你可以使用state_dictionary.get(key)不拋出錯誤,如果它不存在,沒有得到。比嘗試抓住更好。