How to exit an if clause

前端 未结 13 1752
故里飘歌
故里飘歌 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 08:47

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

提交回复
热议问题