3

I am unable to understand the use of the pass statement in Python.

I have found some sample code here in which there is a pass statement but I am unable to figure out what it is useful for in this context:

for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :', letter 
8
  • 3
    Where did this sample code come from? I think you should avoid that source. Commented Feb 26, 2014 at 8:31
  • 2
    Also, read the docs: docs.python.org/2/tutorial/controlflow.html#pass-statements Commented Feb 26, 2014 at 8:33
  • @TimPietzcker i found this code at -tutorialspoint.com/python/python_pass_statement.htm Commented Feb 26, 2014 at 8:38
  • 4
    Thanks - that's a wonderful example of how a tutorial should not be done. They are explaining that "the pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.", and then they proceed to give an example where the pass statement is not required syntactically because you do want code to execute... Commented Feb 26, 2014 at 8:44
  • 1
    ...I've just looked at a couple other pages in the tutorial. They are chock full of errors, inelegancies, often fail to make the point (for example why one would use a tuple instead of a list) etc. - choose a better tutorial (like the official Python tutorial). Commented Feb 26, 2014 at 8:49

3 Answers 3

7

A pass is a NOP in Python. It has no effect on efficiency. It is merely used as a syntactic placeholder to mark an empty block.

You can use the dis module to see that there is no difference in the generated code when using the pass-statement:

>>> from dis import dis >>> def f(x): return x >>> dis(f) 2 0 LOAD_FAST 0 (x) 3 RETURN_VALUE 

Now, again but with a pass-statement added:

>>> def f(x): pass return x >>> dis(f) 3 0 LOAD_FAST 0 (x) 3 RETURN_VALUE 

Notice that the generated code is no different with the pass-statement.

Hope that helps. Good luck :-)

Sign up to request clarification or add additional context in comments.

Comments

5

The pass statement is an empty statement. It does absolutely nothing. The way you have used it, it makes no difference whatsoever.

pass is mainly used as a placeholder statement. Suppose you have a function which you plan to implement later. Well, you can't just leave it blank cause that's improper syntax. So, you use pass.

def spam(): pass # i'll implement this later 

A similar use would be in empty loops.

for i in xrange(10): pass # just add some delay maybe? 

Comments

1

When we have nothing to do in loop area, and then run the program we get an error. to eliminate this error we can use pass statement.error

for i in range(5): # when we execute this code we find error. for i in range(5): # no error pass 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.