Python Match


What is the Python Match statement?

Python introduced the match statement to make multi-case decision-making easier. Instead of writing long chains of if, elif, and else, the match structure lets you describe different patterns clearly. It works especially well when one value needs to be compared to many possible cases. It also helps organize code that handles structured data, like tuples or dictionary-like objects.

For example, if you want to check a user’s choice in a menu, match feels cleaner and more readable than multiple elif lines.

Why should I use Match instead of multiple Elif?

You should use match when:

  • You are handling many different values.

  • The conditions depend mainly on the same variable.

  • You want the code to look cleaner and easier to scan.

  • You want to use patterns like ranges, literals, or structured data.

It doesn’t replace If…Else entirely. Instead, it offers a better tool for certain situations, especially when you're matching patterns.

What is the basic syntax of Python Match?

The structure is simple:

match value:
    case pattern1:
        # code
    case pattern2:
        # code
    case _:
        # default case
  • match is followed by the value you're checking.

  • Each case is a pattern to test.

  • _ acts as a wildcard, similar to "else," matching anything.

Example:

day = "Monday"

match day:
    case "Monday":
        print("Start of the week.")
    case "Friday":
        print("Weekend coming.")
    case _:
        print("Regular day.")

Only the block under the first matching case runs.

How do simple literal matches work?

Literal matching is the most common use. You compare a variable to exact values like names, colors, commands, menu numbers, etc.

Example:

choice = 2

match choice:
    case 1:
        print("Start")
    case 2:
        print("Settings")
    case 3:
        print("Exit")
    case _:
        print("Invalid choice")

This is cleaner than writing:

if choice == 1:
    ...
elif choice == 2:
    ...

How do I match multiple values in one case?

You can combine multiple literal values in one line using the | operator.

Example:

color = "red"

match color:
    case "red" | "maroon" | "crimson":
        print("Warm shade")
    case "blue" | "navy":
        print("Cool shade")
    case _:
        print("Unknown color")

This style reduces repetitive patterns and keeps the logic compact.

How do wildcards work?

A wildcard (_) catches anything that hasn’t matched earlier. It behaves like a final fallback.

Example:

status = "unknown"

match status:
    case "online":
        print("User is active")
    case "offline":
        print("User is not active")
    case _:
        print("Status unavailable")

Use the wildcard when you need a safe final response.

How do I use guards (conditions inside cases)?

Guards allow extra checks using if after the pattern.

Example:

score = 87

match score:
    case s if s >= 90:
        print("Excellent")
    case s if s >= 75:
        print("Good")
    case s if s >= 60:
        print("Average")
    case _:
        print("Needs improvement")

This works like clean conditional grouping. It’s easier to read than stacking condition checks.

How do I match data structures like tuples?

match can also check patterns inside tuples. This is helpful when handling coordinates or grouped values.

Example:

point = (0, 5)

match point:
    case (0, y):
        print("Point on x-axis at", y)
    case (x, 0):
        print("Point on y-axis at", x)
    case (x, y):
        print(f"Point at ({x}, {y})")

Patterns break down the structure and assign values to variables automatically.

How does Match compare with If…Else?

Here’s a quick comparison:

Feature Match If…Else
Clean multi-case structure Yes No
Uses patterns Yes Limited
Good for structured data Yes Not ideal
Checks many conditions on same value Best fit Can get messy
Supports nested logic Yes Yes

Match isn’t always a replacement, but it’s better whenever you’re checking the same variable against many possible outcomes.

How do I use Match in real projects?

You’ll use it in many situations:

  • Menu selections

  • Command processing

  • Input classification

  • API response handling

  • Game options

  • Routing logic

  • Status checks

Here’s an example for menu handling:

option = input("Enter 1, 2 or 3: ")

match option:
    case "1":
        print("New file created.")
    case "2":
        print("File saved.")
    case "3":
        print("Program closed.")
    case _:
        print("Invalid option.")

This small pattern makes menu systems easier to maintain.

How do I avoid mistakes when using Match?

  • Always place specific cases first.

  • End each case line with a colon.

  • Use _ only as the catch-all.

  • Don’t confuse guards with conditions.

  • Keep patterns simple and clear.

Match is strict about patterns. If the pattern is too complex or vague, Python may not behave as expected.

Example: checking login states

Here is a complete example similar to a small login flow:

state = "wrong-password"

match state:
    case "success":
        print("Login successful")
    case "wrong-password":
        print("Password is incorrect")
    case "no-user":
        print("User not found")
    case _:
        print("Unknown state")

Code like this appears in many real-world applications.

Summary of the Tutorial

The Python Match statement gives you a cleaner and more structured way to handle multiple outcomes. It checks a value against several patterns and runs the first matching block. You can match simple values, combine cases with |, use guards for extra conditions, and even handle structured data like tuples. Match keeps your code readable and organized, especially when many decisions depend on a single value.


Practice Questions

  1. Write a program that takes a day name from the user and uses match to print whether it is a weekday or weekend.

  2. Ask the user to enter a number from 1 to 5 and use match to print a different description for each number.

  3. Create a menu-driven program using match with options like “add”, “edit”, “delete”, and “exit”.

  4. Ask the user for a color and use match with multiple patterns ("red" | "maroon" | "crimson") to group similar shades.

  5. Write a program that takes a student’s marks and uses match with guards (case s if s >= ...) to print the grade.

  6. Take a tuple input like (0, 5) or (3, 0) and use match to check if the point lies on the x-axis, y-axis, or somewhere else.

  7. Ask the user for a login state (“success”, “wrong-password”, “no-user”) and print the correct message using match.

  8. Create a small calculator where the user enters an operator like +, -, *, / and match selects the operation.

  9. Ask the user for a vehicle type like “car”, “bike”, “truck”, “bus” and use match to display the tax category.

  10. Write a program that takes a fruit name from the user and uses a wildcard case (_) to catch any fruit not listed in the defined cases.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top