Match Case Statement with Python If Condition
We also can use the Python If condition along with match case statement when instead of matching the exact value, we use a condition. Based on the condition, if the value is True and matches the case pattern, the code block is executed.
Example: In this example, we will use if condition along with match case statement to check if a number entered bt the user id positive, negative or zero.
# python match case with if condition
def runMatch():
num = int(input("Enter a number: "))
# match case
match num:
# pattern 1
case num if num > 0:
print("Positive")
# pattern 2
case num if num < 0:
print("Negative")
# default pattern
case _:
print("Zero")
runMatch()
Output:
Enter a number: -15
Negative
Python Match Case Statement
Developers coming from languages like C/C++ or Java know that there is a conditional statement known as a Switch Case. This Match Case is the Switch Case of Python which was introduced in Python 3.10. Here we have to first pass a parameter and then try to check with which case the parameter is getting satisfied. If we find a match we will execute some code and if there is no match at all, a default action will take place.