Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is `pass` necessary in a Python if statement? [duplicate]

Tags:

python

syntax

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?

like image 267
wz-billings Avatar asked Sep 21 '25 05:09

wz-billings


1 Answers

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.

like image 170
Havenard Avatar answered Sep 22 '25 20:09

Havenard