If else在try/except b中编码帮助

2024-09-26 18:11:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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}$

Tags: 代码helloif错误resultelsemarkbye
3条回答

您可以添加另一个,但不指定它应该处理什么异常。在

try:
   # do something
except KeyError:
   # do something because of the Keyerror
except:
   # do what you need to do if the exception is not a KeyError

一个合理的选择是初始化result = None,然后测试if result is None:。在

使用None比使用空字符串要好,因为有一天您可能希望dictionary值是空字符串,加上None对于代码的普通读者来说可能更清楚。在

也可以跳过try except,使用if theKey in someDict:。在

someDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}   # corrected dict name
result = ""
theKey = raw_input("Enter some key: ")
try:                    # just try the code where the error could be
    val = someDict[theKey]
except KeyError:        # corrected exception name and indent level
    result = "hello"    # corrected syntax
else:                   # corrected indent level
    result = result + "" + "done"       # why add "" ?
print result 

这对你有用吗?在

相关问题 更多 >

    热门问题