【发布时间】:2011-01-05 09:28:04
【问题描述】:
过早退出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 子句,我认为退出会跳过它们。
【问题讨论】:
-
第二个代码示例——你知道
elif吗? -
“或者,我可以编写我的代码以使 if 子句尽可能小,并且不需要任何退出。” ——当然这将是最好的行动方案。 :-)
-
@Craig McQueen:我愿意,但是说我想让代码在条件语句之间执行?例如。
if a: #stuff; #stuff_inbetween; if b: #stuff;中间代码依赖于not a,但不依赖于b。 -
你好,请不要忘记
elifstackoverflow.com/a/2069680/7045119
标签: python control-flow