0

http://www.learnpython.org/page/Exception%20Handling

我无法修复代码以显示答案try/except

给定代码:

#Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}

#Function to modify, should return the last name of the actor<br>
def get_last_name():
   return actor["last_name"]

#Test code
get_last_name()
print "All exceptions caught! Good job!"<br>
print "The actor's last name is %s" % get_last_name()

但是,我能够使用以下代码获得正确的显示,但是它不使用try/except

#Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}
x = actor.pop("name")
#Function to modify, should return the last name of the actor<br><br>
def get_last_name():
   name = x.split(" ")
   last_name = name[1] #zero-based index
   return last_name

#Test code
get_last_name()
print "All exceptions caught! Good job!"
print "The actor's last name is %s" % get_last_name()
4

1 回答 1

1

字典中没有last_name键,所以在最后一行调用时会抛出异常。actorKeyErrorget_last_name()

def get_last_name():
   try:
      return actor["last_name"]
   except(KeyError):
      ## Handle the exception somehow
      return "Cleese"

"Cleese"显然,您可以使用上面编写的逻辑来拆分“名称”字段并从中派生姓氏,而不是对字符串进行硬编码。

于 2013-05-22T02:46:44.877 回答