如何退出if子句

时间:2010-01-15 05:20:54

标签: python control-flow

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

13 个答案:

答案 0 :(得分:77)

(此方法适用于if,多个嵌套循环和其他您无法轻松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()
    ...

答案 1 :(得分:42)

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

(请不要实际使用它。)

答案 2 :(得分:18)

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

答案 3 :(得分:9)

您可以使用例外模拟goto的功能:

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

免责声明:我的意思是提醒您注意以这种方式做事的可能性,而在正常情况下,我绝不认为它是合理的。正如我在关于这个问题的评论中提到的那样,构建代码以便首先避免拜占庭条件是可取的。 : - )

答案 4 :(得分:5)

可能是这个吗?

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 :(得分:4)

一般来说,不要。如果你正在筑巢“ifs”并打破它们,那你就错了。

但是,如果你必须:

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稍后。

答案 6 :(得分:3)

对于实际问的内容,我的方法是将那些if放在一个循环的循环中

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

答案 7 :(得分:1)

你所描述的实际上是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

答案 8 :(得分:1)

还有另一种方法不依赖于定义函数(因为有时对于小的代码段而言,可读性较低),不使用额外的外部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的中间含义之后,它很容易阅读,都放在同一位置,并且缩进相同。

它应该非常有效。

答案 9 :(得分:0)

所以在这里我理解你试图突破外部如果代码块

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

答案 10 :(得分:0)

在没有其他方法的情况下唯一适用的方法是import React, { Component, actions } from "react"; import { connect } from "react-redux"; class CardTradeSim extends Component { constructor(props) { super(props); this.state = { ObtenerdataETH: [], ObtenerdataBTC: [], ObtenerdataXRP: [], }; } // Arrow function DevuelveValorCrypto = (testing) => { console.log("check received: ", testing); const TipoCrypto = testing; let test123 = this.state.ObtenerdataETH.price; console.log("check received: valor de test123", test123); return <DIV>bla bla </DIV>; }; render() { <DevuelveValorCrypto testing="..." />; } } const mapStateToProps = (state) => { return { token: state.token, //selectvalue: state.value }; }; //Dispaching to STORE: const mapDispatchToProps = (dispatch) => { return { onSelectCrypto: (value) => dispatch(actions.SelectCrypto(value)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(CardTradeSim); ,如下例所示

select
    max(t1.stage_id),
    t1.job_id
from
    stage_snapshots as t1
left join stage_snapshots as t2
    on t1.job_id = t2.job_id and 
     (t1.date < t2.date or 
       (t1.date = t2.date and 
        t1.job_id < t2.job_id))
where 
    t1.active_count > 0 and 
    t2.date is null
group by
    t1.job_id

答案 11 :(得分:-1)

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

print(DateTime(2020,03,12).add(new Duration(days: 17)));
print(DateTime(2020,03,12).add(new Duration(days: 18)));

答案 12 :(得分:-2)

在if条件中使用return将使您退出函数, 这样您就可以使用return来打破if条件。