Python pass Statement



Python pass Statement

Python pass statement is used when a statement is required syntactically but you do not want any command or code to execute.

It is a null operation; nothing happens when it executes. Python pass statement is also useful in places where your code will eventually go, but has not been written yet, i.e., in stubs).

Syntax of pass Statement

pass

Example of pass Statement

The following code shows how you can use the pass statement in Python −

for letter in 'Python':
   if letter == 'h':
      pass
      print ('This is pass block')
   print ('Current Letter :', letter)
print ("Good bye!")

When the above code is executed, it produces the following output

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Dummpy Infinite Loop with pass Statement

This is simple enough to create an infinite loop using pass statement. For instance, if you want to code an infinite loop that does nothing each time through, do it with a pass.

Example

while True: pass                  # Type Ctrl-C to stop

Because the body of the loop is just an empty statement, Python gets stuck in this loop. As explained earlier pass is roughly to statements as None is to objects — an explicit nothing.

Using Ellipses ... as pass Statement Alternative

Python 3.X allows ellipses coded as three consecutive dots ...to be used in place of pass statement. This ... can serve as an alternative to the pass statement.

Example

For example if we create a function which does not do anything especially for code to be filled in later, then we can make use of ...

def func1():
    ...                   # Alternative to pass

def func2(): ...          # Works on same line too

func1()                   # Does nothing if called
func2()                   # Does nothing if called

Advertisements