Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Starting in Python 3.10, Python introduced Structural Pattern Matching using the match and case keywords (formalized in PEP 634 and PEP 636).
If you have learned other programming languages like C, C++, or Java, you might be familiar with a switch-case statement. Python's match-case is not just a simple switch—it is a superset that allows structural pattern matching while keeping everyday value checking extraordinarily clean, expressive, and readable.
match-case Instead of Long if-elif-else Chains?When checking a single variable against many possible discrete values, multiple elif statements can quickly become repetitive and cluttered:
if-elif-else):match-case):Notice how much cleaner and structured the match-case code appears.
match-casematch SubjectThe expression right after match is evaluated once:
case _:)The underscore _ acts as the wildcard / default fallback case.
case branches match, the case _: branch executes.else: block in an if-elif chain.case _: at the very end. Putting it earlier will catch all subsequent cases, triggering a syntax error or dead code.|)In modern Python, you can match multiple alternatives in a single case using the pipe symbol | (logical OR):
if-elif vs match-case| Scenario | Recommended Approach | Reason |
|---|---|---|
Checking ranges (score >= 90) | if-elif-else | Direct mathematical comparison |
| Multiple independent conditions | if-elif-else | Independent boolean logic |
| Discrete string/number commands | match-case | Highly readable and declarative |
| Validating data shapes & tuples | match-case | Deconstructs structure effortlessly |
Write a Python script that asks the user to enter a payment mode:
"UPI" or "GPAY" or "PAYTM" → Print: "Processing instant QR payment.""CARD" or "DEBIT" or "CREDIT" → Print: "Redirecting to banking gateway.""CASH" → Print: "Please pay at the MSK Institute admissions desk."match-case statement?_ in a case clause?case branch?case matches and there is no case _: wildcard present?match-case match string literals, integer numbers, and boolean values?In the next lesson, we will put our conditional logic into practice with Project: Grading System (12: Conditional Statements).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Ternary Operators | Project: Grading System |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.