-
Hajipur, Bihar, 844101
Python's match
statement is used for pattern matching. It was introduced in Python 3.10 and is similar to the switch-case statements in other programming languages.
The match
statement evaluates an expression and compares it against patterns specified in case
blocks.
match variable:
case pattern1:
# code block
case pattern2:
# code block
case _:
# default block
match
keyword evaluates the value.
case
is used to compare against different possible matches.
_
is the wildcard pattern that acts like default
.
x = 2
match x:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case _:
print("No match")
fruit = "banana"
match fruit:
case "apple":
print("Apple")
case "banana":
print("Banana")
case "cherry":
print("Cherry")
case _:
print("Unknown fruit")
day = "Saturday"
match day:
case "Saturday" | "Sunday":
print("Weekend")
case "Monday":
print("Start of week")
case _:
print("Weekday")
point = (0, 5)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print("X =", x)
case (0, y):
print("Y =", y)
case (x, y):
print(f"X = {x}, Y = {y}")
You can use conditions with if
inside case
.
value = 20
match value:
case x if x > 10:
print("Greater than 10")
case _:
print("10 or less")
Available in Python 3.10 and later.
The _
case matches any value not handled by earlier cases.
match
is more powerful than traditional switch-case because it supports pattern matching.
Q1. Write a Python program to use match
to check if input is "yes", "no", or "maybe" and print the response.
Q2. Write a Python program to match numbers 1–5 and print their word equivalents (e.g., 1 → "One").
Q3. Write a Python program to match a tuple like (0, y)
and print the value of y
.
Q4. Write a Python program to use match
to check if the entered day is a weekend or not.
Q5. Write a Python program to accept a grade (A, B, C) and print remarks based on the grade using match
.
Q6. Write a Python program to use |
in a case to group multiple values (e.g., "yes" | "y"
for Yes).
Q7. Write a Python program to use a guard condition with match
(e.g., case x if x > 50:
) to print a message.
Q8. Write a Python program to match the number of sides and print the name of the shape (e.g., 3 → Triangle).
Q9. Write a Python program to create a simple calculator using match
to handle operations like +
, -
, *
, /
.
Q10. Write a Python program to match the input month (e.g., "March"
) and print its season.
Q1: Which Python version introduced match?
Q2: What symbol is used to represent the default case?
Q3: What does the pipe | operator do in a match statement?
Q4: Which of the following is valid inside a match block?
Q5: What will happen if no case matches and there is no _ case?
Q6: Can you match tuple values using match?
Q7: What does case x if x > 10: represent?
Q8: What does this block do: match x:?
Q9: Can match replace a long if-elif chain?
Q10: What is the role of _ in a match block?