gpt4 book ai didi

python - 在 try block 中返回 try/else

转载 作者:IT老高 更新时间:2023-10-28 21:34:48 26 4
gpt4 key购买 nike

我在 python 中遇到了一个奇怪的行为。我在 python 帮助或 SE 中找不到有关此的信息,所以这里是:

def divide(x, y):
print 'entering divide'
try:
return x/y
except:
print 'error'
else:
print 'no error'
finally:
print 'exit'

print divide(1, 1)
print divide(1, 0)

输出:

entering divide
exit
1
entering divide
error
exit
None

如果在 try 中返回值,python 似乎不会进入 else block 。但是,它总是会出现在 finally block 中。我真的不明白为什么。有人可以帮我解决这个逻辑吗?

谢谢

最佳答案

http://docs.python.org/reference/compound_stmts.html#the-try-statement

The optional else clause is executed if and when control flows off the end of the try clause.

Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

关于python - 在 try block 中返回 try/else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7442133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com