Satya
Satya

Reputation: 131

Where to use pass statement in python?How can i use pass statement efficiently?

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

Upvotes: 3

Views: 296

Answers (3)

Ezra Roman
Ezra Roman

Reputation: 11

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

Upvotes: 1

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

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?

Upvotes: 5

Raymond Hettinger
Raymond Hettinger

Reputation: 226346

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 :-)

Upvotes: 7

Related Questions