[英]Is there a way to continue my script after running an if statement to catch anomaly in Python?
我试过在网上搜索,但我似乎找不到任何可以回答这个问题的东西。
我目前有一个正在运行的脚本,我正在使用 if 语句来捕获异常。
if test <= limit:
return True
这按预期工作,但我希望将所述代码减少为一行,例如
return True if test <= limit else [continue with script]
但我不知道在 [continue with script] 部分放什么。
当然,您可以这样做,至少在原则上是这样,尽管它不是真正的一行代码。 在所有。 这几乎肯定不是你想要的:
class LimitException(Exception):
pass
def LimitExceptionRaiser(msg):
raise LimitException(msg)
def f(test, limit):
try:
return True if test < limit else LimitExceptionRaiser("Must continue")
except LimitException:
pass
return False
if __name__ == "__main__":
print(f(1, 2)) # -> True
print(f(2, 1)) # -> False
这个解决方案漂亮吗? 下一个必须维护你的代码的人会表扬你吗? 似乎不太可能。
else
后面的任何内容else
必须是一个值,因此我不能简单地将raise Exception()
放在那里,而是必须诱使解释器认为它获得了一个值,即某个其他函数LimitExceptionRaiser
的返回值。 但是这个函数不会返回一个值,它会停止当前的执行行并强行将你拉出它。
再来一次,
def f(test, limit):
if test < limit:
return True
return False
似乎是一个更明智的解决方案(为了澄清,我假设您在函数内部进行了一些额外的计算,否则,您可以简单地执行return test < limit
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.