问题:如何退出if子句

有哪些方法可以过早退出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子句,我认为退出将跳过它们。

What sorts of methods exist for prematurely exiting an if clause?

There are times when I’m writing code and want to put a break statement inside of an if clause, only to remember that those can only be used for loops.

Lets take the following code as an example:

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

I can think of one way to do this: assuming the exit cases happen within nested if statements, wrap the remaining code in a big else block. Example:

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

The problem with this is that more exit locations mean more nesting/indented code.

Alternatively, I could write my code to have the if clauses be as small as possible and not require any exits.

Does anyone know of a good/better way to exit an if clause?

If there are any associated else-if and else clauses, I figure that exiting would skip over them.


回答 0

(此方法适用于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()
    ...

(This method works for ifs, multiple nested loops and other constructs that you can’t break from easily.)

Wrap the code in its own function. Instead of break, use return.

Example:

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()
    ...

回答 1

goto导入goto,标签

如果有条件:
   ...
   如果condition_a:
       # 做一点事
       #然后退出外部if块
       转到.end
   ...
   如果condition_b:
       # 做一点事
       #然后退出外部if块
       转到.end
   #更多代码在这里

标签.end

(请不要实际使用它。)

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

(Don’t actually use this, please.)


回答 2

while some_condition:
   ...
   if condition_a:
       # do something
       break
   ...
   if condition_b:
       # do something
       break
   # more code here
   break
while some_condition:
   ...
   if condition_a:
       # do something
       break
   ...
   if condition_b:
       # do something
       break
   # more code here
   break

回答 3

您可以使用以下方法模拟goto的功能:

try:
    # blah, blah ...
    # raise MyFunkyException as soon as you want out
except MyFunkyException:
    pass

免责声明:我只是想提醒您注意以这种方式做事的可能性,而在正常情况下,我绝不认为这样做是合理的。正如我在对该问题的评论中所提到的那样,到目前为止,最好构造代码以便避免拜占庭条件。:-)

You can emulate goto’s functionality with exceptions:

try:
    # blah, blah ...
    # raise MyFunkyException as soon as you want out
except MyFunkyException:
    pass

Disclaimer: I only mean to bring to your attention the possibility of doing things this way, while in no way do I endorse it as reasonable under normal circumstances. As I mentioned in a comment on the question, structuring code so as to avoid Byzantine conditionals in the first place is preferable by far. :-)


回答 4

可能是这个吗?

if some_condition and condition_a:
       # do something
elif some_condition and condition_b:
           # do something
           # and then exit the outer if block
elif some_condition and not condition_b:
           # more code here
else:
     #blah
if

may be this?

if some_condition and condition_a:
       # do something
elif some_condition and condition_b:
           # do something
           # and then exit the outer if block
elif some_condition and not condition_b:
           # more code here
else:
     #blah
if

回答 5

对于实际提出的要求,我的方法是将这些ifs放入一个单循环的循环中

while (True):
    if (some_condition):
        ...
        if (condition_a):
            # do something
            # and then exit the outer if block
            break
        ...
        if (condition_b):
            # do something
            # and then exit the outer if block
            break
        # more code here
    # make sure it is looped once
    break

测试一下:

conditions = [True,False]
some_condition = True

for condition_a in conditions:
    for condition_b in conditions:
        print("\n")
        print("with condition_a", condition_a)
        print("with condition_b", condition_b)
        while (True):
            if (some_condition):
                print("checkpoint 1")
                if (condition_a):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 2")
                    break
                print ("checkpoint 3")
                if (condition_b):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 4")
                    break
                print ("checkpoint 5")
                # more code here
            # make sure it is looped once
            break

For what was actually asked, my approach is to put those ifs inside a one-looped loop

while (True):
    if (some_condition):
        ...
        if (condition_a):
            # do something
            # and then exit the outer if block
            break
        ...
        if (condition_b):
            # do something
            # and then exit the outer if block
            break
        # more code here
    # make sure it is looped once
    break

Test it:

conditions = [True,False]
some_condition = True

for condition_a in conditions:
    for condition_b in conditions:
        print("\n")
        print("with condition_a", condition_a)
        print("with condition_b", condition_b)
        while (True):
            if (some_condition):
                print("checkpoint 1")
                if (condition_a):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 2")
                    break
                print ("checkpoint 3")
                if (condition_b):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 4")
                    break
                print ("checkpoint 5")
                # more code here
            # make sure it is looped once
            break

回答 6

一般来说,不要。如果要嵌套“ if”并从中断开,则说明这样做是错误的。

但是,如果您必须:

if condition_a:
   def condition_a_fun():
       do_stuff()
       if we_wanna_escape:
           return
   condition_a_fun()
if condition_b:
   def condition_b_fun():
       do_more_stuff()
       if we_wanna_get_out_again:
           return
   condition_b_fun()

注意,这些函数不必在if语句中声明,可以提前声明它们;)这将是一个更好的选择,因为它将避免以后再重构一个丑陋的if / then。

Generally speaking, don’t. If you are nesting “ifs” and breaking from them, you are doing it wrong.

However, if you must:

if condition_a:
   def condition_a_fun():
       do_stuff()
       if we_wanna_escape:
           return
   condition_a_fun()
if condition_b:
   def condition_b_fun():
       do_more_stuff()
       if we_wanna_get_out_again:
           return
   condition_b_fun()

Note, the functions don’t HAVE to be declared in the if statement, they can be declared in advance ;) This would be a better choice, since it will avoid needing to refactor out an ugly if/then later on.


回答 7

实际上,您所描述的是goto语句,通常会对其进行大量平移。您的第二个示例更容易理解。

但是,清洁器仍然是:

if some_condition:
   ...
   if condition_a:
       your_function1()
   else:
       your_function2()

...

def your_function2():
   if condition_b:
       # do something
       # and then exit the outer if block
   else:
       # more code here

Effectively what you’re describing are goto statements, which are generally panned pretty heavily. Your second example is far easier to understand.

However, cleaner still would be:

if some_condition:
   ...
   if condition_a:
       your_function1()
   else:
       your_function2()

...

def your_function2():
   if condition_b:
       # do something
       # and then exit the outer if block
   else:
       # more code here

回答 8

还有另一种方法不依赖于定义函数(因为有时对于小的代码片段而言,其可读性较低),不使用额外的外部while循环(可能需要对注释进行特殊理解,以便乍一看也可以理解) ,不使用goto(…),最重要的是,如果不需要,则让您保持外部的缩进级别。

if some_condition:
   ...
   if condition_a:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
   # keep doing something
   if condition_b:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if:
   # keep doing something

是的,这还需要重新审视其可读性,但是,如果代码段很小,则不需要跟踪任何永远不会重复的while循环,并且在了解了中间if的含义之后,它很容易阅读,所有内容一个位置并具有相同的缩进。

而且它应该非常有效。

There is another way which doesn’t rely on defining functions (because sometimes that’s less readable for small code snippets), doesn’t use an extra outer while loop (which might need special appreciation in the comments to even be understandable on first sight), doesn’t use goto (…) and most importantly let’s you keep your indentation level for the outer if so you don’t have to start nesting stuff.

if some_condition:
   ...
   if condition_a:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
   # keep doing something
   if condition_b:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if:
   # keep doing something

Yes, that also needs a second look for readability, however, if the snippets of code are small this doesn’t require to track any while loops that will never repeat and after understanding what the intermediate ifs are for, it’s easily readable, all in one place and with the same indentation.

And it should be pretty efficient.


回答 9

所以在这里我了解到您正在尝试突破外部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块嵌套其他ifs以执行某些操作

if test_for_false:
    # Exit the code(which is the outer if code)

else:
    if condition_a:
        # Do something

    if condition_b:
        # Do something

So here i understand you’re trying to break out of the outer if code block

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

One way out of this is that you can test for for a false condition in the outer if block, which will then implicitly exit out of the code block, you then use an else block to nest the other ifs to do something

if test_for_false:
    # Exit the code(which is the outer if code)

else:
    if condition_a:
        # Do something

    if condition_b:
        # Do something

回答 10

无需其他方法即可应用此功能的唯一elif示例是以下示例

a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b: 
    print('monthly') 
elif 'quartly' in b: 
    print('quartly') 
elif 'semiannual' in b: 
    print('semiannual') 
elif 'yearly' in b: 
    print('yearly') 
else: 
    print('final') 

The only thing that would apply this without additional methods is elif as the following example

a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b: 
    print('monthly') 
elif 'quartly' in b: 
    print('quartly') 
elif 'semiannual' in b: 
    print('semiannual') 
elif 'yearly' in b: 
    print('yearly') 
else: 
    print('final') 

回答 11

这是处理此问题的另一种方法。它使用单个项目进行循环,使您可以仅使用continue。它避免了不必要的不​​必要的额外功能。并且另外消除了潜在的无限while循环。

if something:
    for _ in [0]:
        # Get x
        if not x:
            continue

        # Get y
        if not y:
            continue

        # Get z
        if not z:
            continue

        # Stuff that depends on x, y, and z

Here’s another way to handle this. It uses a single item for loop that enables you to just use continue. It prevents the unnecessary need to have extra functions for no reason. And additionally eliminates potential infinite while loops.

if something:
    for _ in [0]:
        # Get x
        if not x:
            continue

        # Get y
        if not y:
            continue

        # Get z
        if not z:
            continue

        # Stuff that depends on x, y, and z

回答 12

使用return中,如果条件将回报您从功能出来,这样就可以使用回打破的,如果条件。

use return in the if condition will returns you out from the function, so that you can use return to break the the if condition.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。