Match case Statements
'''
A match case statement compares a given variable's value to different shapes, also referred to as the pattern. The main data is to keep on comparing the variable with all the present patterns until it fits into one.
match-case is very similar to if-else statements, but they do have some differences.
The main difference is that,
if-statements are used for general conditions, but match-case is used for specific conditions i.e. discrete values and patterns.
if-statements could be lengthy for coarse conditions, but match-case is more efficient and shorter.
if-statements support logical operators like and, or but match-case does not.
'''
x = int(input("Enter the value of x: "))
# x is the variable to match.
match x:
#if x is 0
case 0:
print("x is zero")
#case with if-condition
case 4 if x % 2 == 0:
print("x % 2 == 0 and case is 4") #Empty case with if-condition
case _ if x!=90:
print(x, "is not 90")
case _ if x!=80:
print(x, "is not 80")
case _:
print(x)
#The default case is executed if the value of x does not match any of the cases.
# It is basically the else-statement in if-else statements.
#We can match multiple cases at once using "OR" operator "|".
#Enter a value of x: 90
#90 is not 80
y = int(input("Enter the value of y: "))
match y:
case 0|1|2|3:
print("y is 0 or 1 or 2 or 3")
case _ if y > 3:
print(y, "is greater than 3")
#Enter the value of y:4
#4 is greater than 3
Comments
Post a Comment