Industry Ready Java Spring Boot, React & Gen AI — Live Course
PythonConditional Statements

Match


Python 3.10 introduced the match statement, a modern and more readable alternative to long if-elif-else chains. It is similar to the switch-case found in languages like C or Java, but more powerful, cleaner, and easier to maintain.

Why Use match?

  • It provides a concise and readable way to compare a variable against multiple values.
  • Eliminates repetitive conditions seen in long if-elif-else blocks.
  • Enhances code clarity and reduces verbosity.
  • Performs direct value matching without needing expressions like num == 1.
  • Supports a fallback case using case _:, which behaves like an else or default clause.

Match_in_Python


Syntax of Match-Case

match variable:
    case value1:
        # statements
    case value2:
        # statements
    case _:
        # default case

Example: Number to Word Conversion

num = 3

match num:
    case 1:
        print("One")
    case 2:
        print("Two")
    case 3:
        print("Three")
    case 4:
        print("Four")
    case 5:
        print("Five")
    case _:
        print("Incorrect")

Output

Three
  • Only the matching case executes.
  • The case _: block handles all unmatched values (default case).

Comparison With if-elif-else

Featureif-elif-elsematch
SyntaxMore verboseMore concise
ReadabilityLower for many conditionsCleaner for value checks
Default behaviorelsecase _
FlexibilityExpression-based logicPattern-based, direct value matching

Key Advantages of Match

  • Provides a much cleaner alternative to long or deeply nested if-elif-else structures.
  • Best suited for direct value comparisons such as menu selections, status checks, and enum-like options.
  • case _ serves as the default fallback, handling any unmatched values.
  • Offers better readability, maintainability, and scalability when dealing with large sets of conditions.

Summary

  • match offers a cleaner and modern alternative to long if-elif chains, making code easier to read and maintain.
  • It enables direct and structured value matching, improving clarity in decision-making logic.
  • case _ acts as the default fallback, handling all unmatched values gracefully.
  • Reduces boilerplate and enhances code organization, especially in programs with many condition checks.

Written By: Muskan Garg

How is this guide?

Last updated on