Hello, there in this article we will discuss how to use pass and match statements in python with some useful examples.
1. Pass Statement :
In Python, the “pass” statement is used as a placeholder when there is a need to have a statement in the code but no action needs to be taken. It is often used as a placeholder in control structures like “if” and “while” statements, and in user-defined functions or classes where the functionality is not yet implemented.
For example, let’s say we want to create a function that takes a number as an argument and returns “even” if the number is even and “odd” if the number is odd. However, we don’t know how to implement the logic yet, so we can use the “pass” statement as a placeholder:
#pass func def even_or_odd(number): if number % 2 == 0: pass else: pass
In this example, we are using the “if” statement to check if the number is even or odd, but we don’t know how to implement the logic yet, so we use the “pass” statement as a placeholder. This way, the code will run without any errors, and we can come back to it later and implement the logic.
Another use case of the pass statement is when creating a class with no methods.
class MyClass: pass obj = MyClass()
MyClass is defined but it has no methods yet, using a pass statement avoids the error and you can create an instance of the class and add methods later on.
A pass statement can also be useful in “while” loops when you want to repeatedly execute a block of code, but don’t want to include any statements in the block.
while True: pass
This creates an infinite loop that does nothing, which is useful in certain cases like waiting for a specific event to occur.
So we can say, the “pass” statement in Python is used as a placeholder when there is a need for a statement in the code but no action needs to be taken. It is often used in control structures, user-defined functions, and classes as a placeholder for future functionality, and in while loops to repeatedly execute a block of code without any statements.
2. Match Statement :
It takes an expression and matches it with successive patterns given as one or more case blocks. Match statements works similarly to the switch case statements
The match case statement has three entities
- match keyword
- one or more clauses
- expression for each case
#match statements def chat(msg): match msg: case 'Hii': return "Welcome to the code hubs, How are you!" case 'How to add Article ?': return "Click on profile -> Add New Article" case 'How to check plagiarism ?': return "Visit duplichecker.com" case _: return "Something's wrong with the internet"
we can also combine multiple cases using the’ | ‘ command
for example case 1 | case 2 | case 3.
you can also provide patterns in the case for example case (0, 1 )
can also assign variable: case (x=0, y=1)
With that, we come to the end for more you can visit the official python website.
Thanks for reading.