对于过早退出if
子句有哪些方法?
有时我在编写代码时,希望在if
子句中放入一个break
语句,但要记住这些语句只能用于循环。
以下面的代码为例:
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子句,我想退出会跳过它们。
(此方法适用于
if
s、多个嵌套循环和其他构造,您无法轻松地break
)将代码包装到它自己的函数中。不要使用
break
,而是使用return
。示例:
(请不要用这个。)
相关问题 更多 >
编程相关推荐