In this tutorial you'll learn about pass statement in Python which acts as a placeholder.
Python pass statement
pass statement is a null operation, when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but you don't want to do any operation.
For example you have an array of numbers and you want to display only those numbers which are less than 100.
numbers = [89, 102, 45, 234, 67, 10, 333, 32] for num in numbers: if num > 100: #do nothing pass else: print('number is', num)
Output
number is 89 number is 45 number is 67 number is 10 number is 32
As you can see here if-else statement is used to check whether number is greater than or 100 or not. In case it is then you do nothing and that is indicated by using pass statement.
In most of the cases where pass statement is used you can very well write the code without using pass statement too but using pass statement does increase readability.
Python pass statement also ensures that indentation error is not thrown. For example suppose there is a Person class where you have a method to display Person data. You are planning to implement method that will fetch Person details from DB so you want to keep a method as a TODO reminder.
class Person: def __init__(self, name, age): print('init called') self.name = name self.age = age def display(self): print('in display') print("Name-", self.name) print("Age-", self.age) def retrieveData(self): #TODO has to be implemented to fetch details from DB person = Person('John', 40) person.display()
But running this class gives an error “IndentationError: expected an indented block”
In such case adding pass statement with unimplemented method ensures that IndentationError is not thrown.
def retrieveData(self): #TODO has to be implemented to fetch details from DB pass
So, you can see that Python pass statement can be used where you need a place holder be it with in a for loop, while loop or if-else statement, after def or even after class and in exception handling too.
pass statement with class
Suppose you are deriving from Exception class to create a user defined exception class with out adding new behavior, then you can just use pass statement.
class MyException(Exception): pass
pass statement with exception handling
If you don’t want to do anything for a specific type of Exception after catching it you can use pass statement.
numbers = [89, 102, 0, 234, 67, 10, 333, 32] for num in numbers: try: result = 1000/num print('Result is',result) except ZeroDivisionError: print('Division by Zero') result = 0 except AttributeError: pass
That's all for this topic pass Statement in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment