如果 python 中的 try 语句成功,则运行代码 [英] running code if try statements were successful in python

查看:58
本文介绍了如果 python 中的 try 语句成功,则运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 python 中是否有一种简单的方法来运行代码,如果 try 语句成功,而不是在 try 语句本身中.那是 else 或 finally 命令的作用吗(我不明白他们的文档)?我知道我可以使用这样的代码:

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.

推荐答案

你想要else:

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

这篇关于如果 python 中的 try 语句成功,则运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆