最佳答案
过早退出 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 语句中,将剩余的代码封装在 big 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 子句,我认为退出会跳过它们。