如何退出if claus

2024-05-16 20:15:05 发布

您现在位置:Python中文网/ 问答频道 /正文

对于过早退出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子句,我想退出会跳过它们。


Tags: andthe方法代码ifexit语句condition
3条回答

(此方法适用于ifs、多个嵌套循环和其他构造,您无法轻松地break

将代码包装到它自己的函数中。不要使用break,而是使用return

示例:

def some_function():
    if condition_a:
        # do something and return early
        ...
        return
    ...
    if condition_b:
        # do something else and return early
        ...
        return
    ...
    return

if outer_condition:
    ...
    some_function()
    ...
while some_condition:
   ...
   if condition_a:
       # do something
       break
   ...
   if condition_b:
       # do something
       break
   # more code here
   break
from goto import goto, label

if some_condition:
   ...
   if condition_a:
       # do something
       # and then exit the outer if block
       goto .end
   ...
   if condition_b:
       # do something
       # and then exit the outer if block
       goto .end
   # more code here

label .end

(请不要用这个。)

相关问题 更多 >