我想知道在 python 中是否有一种简单的方法来运行代码,如果 try 语句成功但不在 try 语句本身中。那是 else 或 finally 命令的作用吗(我不理解他们的文档)?我知道我可以使用这样的代码:
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
但我想知道是否有更短的方法。
最佳答案
你想要else
:
for i in [0, 1]:
try:
print '10 / %i: ' % i, 10 / i
except:
print 'Uh-Oh'
else:
print 'Yay!'
关于python - 如果 try 语句在 python 中成功,则运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2792568/