How to use the pass statement?

前端 未结 15 2498
旧时难觅i
旧时难觅i 2020-11-22 15:03

I am in the process of learning Python and I have reached the section about the pass statement. The guide I\'m using defines it as being a Null sta

15条回答
  •  感情败类
    2020-11-22 15:35

    Besides its use as a placeholder for unimplemented functions, pass can be useful in filling out an if-else statement ("Explicit is better than implicit.")

    def some_silly_transform(n):
        # Even numbers should be divided by 2
        if n % 2 == 0:
            n /= 2
            flag = True
        # Negative odd numbers should return their absolute value
        elif n < 0:
            n = -n
            flag = True
        # Otherwise, number should remain unchanged
        else:
            pass
    

    Of course, in this case, one would probably use return instead of assignment, but in cases where mutation is desired, this works best.

    The use of pass here is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flag is set in the two specifically mentioned cases, but not in the else-case. Without using pass, a future programmer might move flag = True to outside the condition—thus setting flag in all cases.


    Another case is with the boilerplate function often seen at the bottom of a file:

    if __name__ == "__main__":
        pass
    

    In some files, it might be nice to leave that there with pass to allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.


    Finally, as mentioned in other answers, it can be useful to do nothing when an exception is caught:

    try:
        n[i] = 0
    except IndexError:
        pass
    

提交回复
热议问题