Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this:

successful = False
try:
    #code that might fail
    successful = True
except:
    #error handling if code failed
if successful:
    #code to run if try was successful that isn't part of try

but I was wondering if there was a shorter way.

question from:https://stackoverflow.com/questions/2792568/running-code-if-try-statements-were-successful-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

You want else:

for i in [0, 1]:
    try:
        print '10 / %i: ' % i, 10 / i
    except:
        print 'Uh-Oh'
    else:
        print 'Yay!'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...