我正在编写一个脚本,提示用户输入州名。脚本检查状态是否实际在字典中并且返回资本。如果状态不在dic中,则说明字典中没有。我试过尝试除了KeyError,但Python仍然给我一个错误。我做错了什么?
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'
答案 0 :(得分: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 :(得分: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))
您还可以做的一个改进领域是,您现在希望完全大小写匹配。我建议你将词典中的条目更改为 all 小写,当你收到输入时,强制检查也是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')
答案 2 :(得分:0)
你有一个字典,你可以使用state_dictionary.get(key)
来不抛出错误,如果它不存在就得不到。比不得不尝试捕获更好。
答案 3 :(得分:-1)
在try中添加'else'语句除外。它只会在没有异常的情况下执行:
try:
state_dictionary[search_state]
except KeyError:
print ('No such a State')
else:
print (state_dictionary[search_state])