Python Pass Statement
The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not.
The pass statement is typically used as a placeholder, i.e. when the user is unsure of what code to write. As a result, the user simply inserts a pass at that line. When the user does not want any code to be executed, the function pass is used. As a result, the user can simply use the pass in places where empty code is not permitted, such as loops, function definitions, class definitions, or if statements. The user avoids this error by using the pass statement.
The pass statement has no effect. It can be used when a statement is required syntactically but no action is required by the program. As an example:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
Another use for a place pass is as a placeholder for a function or conditional body when working on new code, allowing you to think at a higher level. The pass is silently disregarded:
>>> def initlog(*args):
... pass # Remember to implement this!
Let us consider some more examples where the pass statement can be used.
for letter in 'Python':
if letter == 'h':
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
The output for the above code is as follows:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Pass is a null statement in Python. The interpreter does not ignore a pass statement; however, nothing happens and the statement has no effect.
When you don't write the implementation of a function but want to implement it later, the pass statement comes in handy.
You can use the pass statement to avoid compilation errors.
Let’s use an example to demonstrate how compilation errors can be avoided by using the statement.
We are given a problem with insufficient data as follows: The students with marks more than 50 are passing the test, students with marks less than 20 have daily extra classes, while the faculty still plans about the curriculum for students with marks between 50 and 20, we have to write a code assuming to update the code in the future. Using a pass statement will be helpful as we can simply replace the line after getting the entire information. The code for the same is as follows:
marks = int(input("Please enter your marks: "))
if(marks > 50):
print("You have passed the examination.")
if(marks <= 50 and marks > 20):
if(marks <= 20):
print("You have to attend daily extra classes!")
Let’s see how the code behaves with different values as input.
Please enter your marks: 58
You have passed the examination.
Please enter your marks: 45
Please enter your marks: 12
You have to attend daily extra classes!