Match Notes
Match Notes
Match Notes
1
Example
[ ]: match num:
case 1:
print("One")
case 2:
print("two")
case _:
print("Anything else than 1 and 2")
1.0.5 Pattern containing multiple values like lists , tuple ,etc can be matched
• Match allows sequences to be taken as a pattern
• Sequence in python can be list ( like array), tuple, set, dictionary
• Each case can have different type and number of input values to be matched
• NOTE: if case has fixed values then order of values needs to be maintained!
2
Example
[ ]: itemid_list=[101,105]
match itemid_list:
case [101,105,110]:
print("Three ids discounted order")
case [101,105]:
print("Two ids Discounted order")
case _:
print("Everything else")
3
# point=(99,34)
match point:
case (0, 0):
print("Origin")
case (0, y):
print("Y=",y)
case (x, 0):
print("X=",x)
case (x, y):
print("X=",x, "Y=",y)
case _:
raise ValueError("Not a point")
1.0.8 ‘case’ can extract relevent values from the complete values coming in the pattern
• When sequence like list,tuple, etc is passed then relevant values can be extracted and other
values can be captured as extra
• relevant values can be – all at starting positions – all at ending positions – few at starting
and few at end positions
Example
[ ]: # message="thank you for your services!"
message="It was nice experience, thank you"
match message.split(): # get list of words from the string
case [w1,w2,*_] if (w1 =='thank') and (w2 =='you'):
print("You are welcome!, we would be happy to help futher")
case [*_,w1,w2] if (w1 =='thank') and (w2 =='you'):
print("You are welcome!, we would be happy to help futher")
case _:
4
print("we would be happy to help futher, thank you")
1.0.9 match can be used to identify type of object and find right case for it
• match can work to ientify type and according perform operation
Example
Given list of values, Take one value from list at a time if value is integer or float then add it to
total, if value is string then concat to name , else print message cannot handle value
[ ]: vals=[1,2.1,'i',3,'a',56,'cs',4.4,'d']
total=0
name=""
for value in vals:
match value:
case int() | float():
total +=value
case str():
name += value
print("total is",total)
print("name is ", name)
total is 66.5
name is iacsd
# point = Point(10,10)
point = Point(10,0)
# point = Point(0,10)
# point = Point(0,0)
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print("On Y-axis, Y=",y)
5
case Point(x=x, y=0):
print("On X axis, X=",x)
case Point():
print("Somewhere else in the coordinate system")
case _:
print("Not a point")
On X axis, X= 10
[ ]: set_pattern = {1,2,3}
match set_pattern:
case {1,2,3}: # Syntax error On this line!
print("Set {1,2,3} matched!")
2 Further reference
Python Enhancement proposal (PEP 636) https://peps.python.org/pep-0636/
Documentation https://docs.python.org/3/tutorial/controlflow.html
[ ]: