How to exit an if clause

前端 未结 13 1751
故里飘歌
故里飘歌 2020-12-04 08:45

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

13条回答
  •  一向
    一向 (楼主)
    2020-12-04 09:07

    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
    

提交回复
热议问题