4

Looking at some of the code other people have written for the project I am currently working on, I often see if statements in the following form.

if condition:
    do this
else:
    pass

Is there a reason pass is used here? Could the entire else statement not just be left out? Why would you include the section with pass? Similarly I also see this:

if condition:
    pass
else:
    do this

Why would you write the code this way, when you could do it this way:

if not condition:
    do this

Is there a reason for using the pass command that I am missing, or are these uses of pass superfluous?

2
  • 2
    You're right that else: pass can be removed entirely—and it almost always should be. You're also right that an if …: pass can always be rewritten as if not …: to swap the if and else bits (at which point you can remove the else: pass), and often it should be—but sometimes it just reads better with the positive condition instead of the negative one, and if your condition is pushing the bounds of easy readability, that small difference can be worth it.
    – abarnert
    Aug 19, 2018 at 2:14
  • 1
    By the way, if you're ever not sure whether you have one of those cases, trying reading out the same condition in English (or whatever your native language is). If you feel yourself thinking "Wait, what? Oh, I get it…", or thinking of the antonym for one of the words, you've got one too many negations. That intuition is usually pretty consistent between different people, and between different languages—even programming and math, even though (at least when I was studying this stuff a thousand years ago) the actual rule for "one too many" is surprisingly hard to codify.
    – abarnert
    Aug 19, 2018 at 2:25

2 Answers 2

3

pass is usually a "to do" placeholder. In Python you cannot declare functions without implementation or any code block without a body for that matter, for example if condition: (do nothing), so you just put pass there to make it valid. pass does nothing.

2

Use it when you need to handle a condition in which you don't want to do anything, like:

try:
    os.mkdir(r'C:\FooBar')
except FileExistsError:
    pass
else:
    os.mkdir(r'C:\FooBar\Baz')
finally:
    print('Wazoooo')

Not the answer you're looking for? Browse other questions tagged or ask your own question.