简体   繁体   中英

If else code help in try/ except block

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 

I understand the try block you can insert and code to try and see what error comes up, and the error then can be caught by the except block. I am trying to figure out the best way to insert a if / else in the try and except block for the same key error that is present in this code. I was thinking that i could just replace the try and except with If/else or is it possible to just add a if/else in the try and except. Any help on how to insert a if/else into this code for key error would be greatly appreciated. So basically i want to add a if/else code into the try and except block for the same key error.

 SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
    try: 
        result = "" #could i insert something like if result == "" : #for this line?
        theKey = raw_input("Enter some key: ")
        val = someDict[theKey]
        except keyErrorr:
            result "hello"
        else:
            result = result + "" + "done"
        print result 

One reasonable option is to initialize result = None , then test if result is None: .

It's better to use None than the empty string, since someday you might want a dictionary value to be the empty string, plus None is probably clearer to the casual reader of your code.

You could also just skip the try-except, and use if theKey in someDict: .

you can add another except without a specification what exception it should handle.

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

does this work for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM