3

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?

wzbillings
  • 364
  • 4
  • 14
  • 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 '18 at 02: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 '18 at 02:25

2 Answers2

2

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.

Havenard
  • 27,022
  • 5
  • 36
  • 62
1

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')
pstatix
  • 3,611
  • 4
  • 18
  • 40