How to exit an if clause

前端 未结 13 1764
故里飘歌
故里飘歌 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:06

    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.

提交回复
热议问题