DEV Community

Aditi Sharma
Aditi Sharma

Posted on

Day 3 Exploring the Wildcard `_` in Python’s Match Statement

Hello dev community 👋

This is Day 3 of my Python learning journey, and today I explored the wildcard _ in the match statement (a feature introduced in Python 3.10).

🔹 What is the Match Statement?

The match statement is Python’s version of pattern matching (similar to switch in other languages, but more powerful).

It lets you compare a value against multiple patterns, executing code for the first matching case.

🔹 The Wildcard _

The _ is a special pattern that matches anything.

It’s often used as the “default case” → when no other condition is met.

🔹 Benefits of Using _ in Match Statements

  • ✅ Clean fallback handling (like a default case)
  • ✅ Reduces unnecessary conditions
  • ✅ Improves readability over long if-elif-else chains
  • ✅ Unique because it matches everything but discards the value

🖥 Coding Practice


python
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Something else"

print(http_status(200))  # OK
print(http_status(404))  # Not Found
print(http_status(500))  # Something else
Enter fullscreen mode Exit fullscreen mode

Top comments (0)