存在哪些过早退出if
子句的方法?
有时我在编写代码并想在子句中放置一条break
语句if
,只是要记住那些只能用于循环。
让我们以下面的代码为例:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
我可以想到一种方法来做到这一点:假设退出情况发生在嵌套的 if 语句中,将剩余的代码包装在一个大的 else 块中。例子:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
else:
...
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
这样做的问题是更多的退出位置意味着更多的嵌套/缩进代码。
或者,我可以编写代码以使if
子句尽可能小,并且不需要任何退出。
有谁知道退出if
条款的好/更好的方法?
如果有任何关联的 else-if 和 else 子句,我认为退出会跳过它们。