Python pass statement keyword
Pass statements do nothing, they are placeholders. The pass statements does not perform any operation
So why pass statements?
Python requires indenting for functions, so to have an empty function the pass
statement is required.
Related course: Complete Python Programming Course & Exercises
Why do we need pass statement?
When you are writing a program and the implementation part of the idea is not finished, then you can use the pass statement to occupy the place.
(it can be used as a marker, is to be completed later code).
For example, the following:
def play_python():
pass
Define a function play_python()
, but the body part of the function is not finished yet. It cannot be left empty without writing content, so pass
can be used instead of taking a place.
An empty function is not allowed, because Python expects indention, so there pass
can be inserted.
If you try to write a function that doesn't have indention, it'll throw an indention error.
>>> def f(x):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
>>>
Pass statements in the loop
Pass is also often used to write an empty body for a loop. Say you want an infinite loop of a while statement, with no operation required for each iteration, you could write it like this
while True:
pass
Pass statement comparison
Take the if statement, for example, in C or C++/java:.
if(true)
;//do nothing
else
{
//do something
}
The equivalent for python would be this.
if True:
pass #do nothing
else:
pass #do something
Can we have multiple pass statements in a function?
Yes you can (see the example above).
You can also have a pass statements like this:
def f(x):
pass
print("hello")
pass
print("world")
pass
Why is this allowed?
Because pass
does not terminate the function, it's just required because Python's syntax needs indention.
Why do we need pass statement?
To summarize:
-
Python pass statement is required when creating an empty function or empty code lbock
-
The primary reason for using the pass statement is when you want to write the code later on
-
The pass statement does not do anything, it's just a place holder