Python is an effective programming language to get things done in an absolute manner. It provides many built-in modules, statements, and functions to perform various specific tasks. The pass statement in Python works in the same way as a placeholder does for a text field in a web form. It plays the same role as a null play in any programming language. When the Python interpreter executes the pass statement, nothing happens. It is useful to place a pass statement when we syntactically require a statement and do not want to execute it. As its name suggests, it passes the control to the next statement.
The main difference between the comment and pass statement is that the Python interpreter completely ignores the comments, whereas, the pass statement is not ignored. This article explains the use of the pass statement in detail.
Syntax of pass statement
The syntax of the pass statement is as follows:
Examples
We put the pass statement in loops, functions, conditional statements, and classes where the empty code is not allowed. For example, we have declared a function and we have not implemented its body yet, but we want to implement its functionality in the future. A function in Python cannot have any empty body. The Python interpreter will show an error. In this specific case, we could put pass statements to utilization which would actually not perform anything. Now, let’s move on and see an example of a pass statement.
#creating a function
def caclculatesum():
pass
Output
When we execute the above program, the Python interpreter does not show any error and nothing happens.
Let’s use the pass statement in a class. Pass statement is just a placeholder for future code.
#creating a class
class numbers:
pass
Now, let’s use the pass statement in for loop. If we make an empty for loop, then the interpreter will throw an error. First, let’s make an empty for loop without a pass statement and see what happens.
#creating an empty for loop
my_list = ['l','i','n','u','x','h','i','n','t']
for x in my_list:
Output
In this case, the Python interpreter shows an error “SyntaxError”.
Now let’s use the pass statement in the loop.
#creating an empty for loop
my_list = ['l','i','n','u','x','h','i','n','t']
for x in my_list:
#using pass statement
pass
Output
By adding the pass statement, if we have get rid of error.
Let’s take another example, and use the pass statement inside the for loop when a given condition is true.
#creating an empty for loop
my_list = ['l','i','n','u','x','h','i','n','t']
for x in my_list:
if(x == 'n'):
#using pass statement
pass
else:
print(x)
Output
The program flow transfers to the next iteration when the given statement is true.
Conclusion
Pass statement is used as a placeholder for future code. It is used when we have to put the empty code inside a class, function, condition statement, or loop. This article describes the pass statement with examples.
from Linux Hint https://ift.tt/2IcDd3W
0 Comments