python - LearnPython.org Tutorial (Exception Handling) -


http://www.learnpython.org/page/exception%20handling

i having trouble fixing code display answer using try/except

given code:

#handle exceptions! #setup actor = {"name": "john cleese", "rank": "awesome"}  #function modify, should return last name of actor<br> def get_last_name():    return actor["last_name"]  #test code get_last_name() print "all exceptions caught! job!"<br> print "the actor's last name %s" % get_last_name() 

i able correct display following code, not use try/except

#handle exceptions! #setup actor = {"name": "john cleese", "rank": "awesome"} x = actor.pop("name") #function modify, should return last name of 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! job!" print "the actor's last name %s" % get_last_name() 

there no last_name key in actor dictionary, throw keyerror exception when call get_last_name() on last line.

def get_last_name():    try:       return actor["last_name"]    except(keyerror):       ## handle exception somehow       return "cleese" 

obviously instead of hard coding "cleese" string use logic wrote above split "name" field , derive last name it.


Comments

Popular posts from this blog

user interface - Python attempting to create a simple gui, getting "AttributeError: 'MainMenu' object has no attribute 'intro_screen'" -

jquery - Common JavaScript snippet to share files on Google Drive, Dropbox, Box.net or SkyDrive -

Android Gson.fromJson error -