SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
try:
result = ""
theKey = raw_input("Enter some key: ")
val = someDict[theKey]
except keyErrorr:
result "hello"
else:
result = result + "" + "done"
print result
我理解try块,您可以插入并编写代码来尝试查看出现了什么错误,然后错误可以被except块捕获。我正试图找出在try and except块中插入if/else的最佳方法,以解决此代码中出现的同一个键错误。我在想我可以用If/else替换try和except,或者可以在try和except中添加If/else。如果您有任何关于如何在代码中插入if/else来处理密钥错误的帮助,我们将不胜感激。所以基本上我想为同一个键错误在try和except块中添加if/else代码。在
^{pr2}$
您可以添加另一个,但不指定它应该处理什么异常。在
一个合理的选择是初始化
result = None
,然后测试if result is None:
。在使用None比使用空字符串要好,因为有一天您可能希望dictionary值是空字符串,加上None对于代码的普通读者来说可能更清楚。在
也可以跳过try except,使用
if theKey in someDict:
。在这对你有用吗?在
相关问题 更多 >
编程相关推荐