Python

Match Case Statement in Python

Click for All Topics

Match Case Statement in Python

Python 3.10 introduced something cool called match case. It’s a bit like the switch case you might have heard about in other programming languages. Prior to Python 3.10, the language didn’t include an official switch-case feature. To fill this gap, developers had several other choices, like if-else statements and dictionaries, to achieve similar results.

What are Switch-Case Statements?

A switch case statement is like a tool in programming that checks a specific situation and does something if that situation is true. It’s a way for a program to make decisions and do different things depending on what’s happening.

While the switch case is like a simple tool, Python’s match case is even more amazing! it is like a superhero tool that can do all sorts of fancy tricks with your data!

What is a match-case statement?

Imagine match-case as a super smart detective for your computer. It can look at information and understand how it’s put together, like solving a puzzle. This detective can handle really tricky situations – not just basic stuff. It’s like having magic glasses that let your program see hidden things inside the information.

Also, this special tool is smart. It doesn’t just tell you if you’re right or wrong. If you’re right, it can even tell you special things about the thing you found. It’s like magic!

This idea is inspired by games where you match shapes or patterns. You know, like when you have puzzle pieces and you find the one that fits perfectly.

What is the difference between ‘match-case’ and ‘if-else statements?

Match case – is designed for specific pattern matching and concise handling of cases. It’s optimal for straightforward situations where values match patterns.

  • If-else – is versatile for handling various conditions. It suits complex scenarios requiring multiple condition evaluations.
  • Choose based on your needs. Match case is clean for clear patterns. If-else handles mixed conditions.

In summary, match case focuses on pattern-based cases, while if-else handles broader conditions with flexibility.

Let’s understand it better with a simple example.

				
					error_code = 404  # defining a variable 'error_code' with the value '404'.

match error_code: # the match keyword is use to start the match case block
    case 202:
        print("this is error no. 202")
    case 303:
        print("this is error no. 303")
    case 505:
        print("oh! this is 505")
    case 404:
        print("error 404: Something went wrong!")
# If error_code matches any of the specified values in the 'case' statements,
# the corresponding code block is executed.

# Output
# error 404: Something went wrong!
				
			

How match-case work?

let’s break it down step by step:

  1. Expression and Patterns: A match statement works with two main things: an “expression” (which is like a value or data) and different “patterns” (which are like templates or descriptions of what you’re looking for).
  1. Comparing with Patterns: It takes this expression and checks it against the patterns one by one. It’s like having a bunch of pictures and trying to find the one that matches what you have.
  1. Similar to Switch but More Powerful: This might remind you of a “switch” statement in languages like C, Java, or JavaScript, where you check a value against different cases. However, the match statement is more powerful and flexible.
  1. Extracting Information: When a pattern matches, not only does the match statement say “Hey, I found a match!” but it can also do something really cool. It can pick out specific parts of the expression and put them into separate “variables” for you to use later.
  1. First Match Wins: It’s smart—it stops checking patterns as soon as it finds the first one that matches. Imagine you’re looking for a specific toy in a box of toys. Once you find it, you don’t keep searching; you stop and play with that toy!
  1. Inspired by Pattern Matching: This whole idea is borrowed from languages like Rust or Haskell, where they’re really good at working with patterns in data. It’s like giving your program the ability to understand the shape and structure of your data and make decisions based on that.

So, in a nutshell, a match statement is a way for your program to look at data, see what it looks like, compare it with different possible shapes, and then do something special based on what it finds. It’s like a detective who solves puzzles by figuring out how things fit together!


Combined Cases in Python Match-Case

Instead of writing separate match-case statements for each pattern, Python allows us to combine some of them using the or (|) operator. This simplifies the code. Match statements are primarily for matching patterns and specific keywords, but you can use the pipe operator to represent conditions within the match statement.

Let’s understand it with some examples

				
					def recommend_destination(preferences):

    match preferences.lower():

        case "beach":
            return "You might enjoy a trip to a juhu beach."

        case "mountains":
            return "Consider visiting leh ladakh."

        case "city":
            return "Explore a vibrant city and its cultural attractions."

        case "adventure":
            return "you can go for hiking."

        case _:  # The 'case_' handles any preference that doesn't match the specified cases. It returns a message indicating that a match couldn't be found for the given preference.
            return "We couldn't find a match for your preferences."

user_preferences = "adventure"
recommended_destination = recommend_destination(user_preferences)
print(recommended_destination)

# Output
# you can go for hiking.
				
			

Python allows you to easily add a default case to your match-case statements. Since Python checks patterns, you can use a throwaway variable like “_” as a placeholder for a catch-all situation. This makes it straightforward to handle unspecified cases.

				
					def classify_age(age):
    match age:
        case 0 | 1 | 2:
            return "newborn"
        case 3 | 4 | 5|6|7:
            return "kid"
        case 8 | 9 | 10|11|12:
            return "Child"
        case 13 | 14 | 15 | 16|17|18:
            return "Teenager"
        case _:
            return "Adult"

age = 9
age_group = classify_age(age)
print("You are classified as", age_group)

# Output
# You are classified as Child
				
			
				
					def season(month_number):
    match month_number:
        case 1|2|11|12 :
            return "Winter"
        case 3|4|5|6:
            return "Summer"
        case 7|8|9|10 :
            return "Monsoon"
        case _:
            return "Invalid month number"

month_num = 9
month_name = season(month_num)
print("The season is:", month_name)

# Output
# The season is: Monsoon
				
			

Creating match-case statements with if-else

In Python, we can use theif condition as an alternative to the match case syntax. If the condition in the “if” statement is true, we execute the corresponding block of code; otherwise, we skip it. This provides a way to handle more specific situations within the matched case.

Let’s understand it with an example

				
					def product(price):
    match price:
        case 70:
            category = "Moderate"
        case _ if price < 10:
            category = "Low-cost"
        case _ if 10 <= price < 50:
            category = "Moderate"
        case _ if 50 <= price < 100:
            category = "Expensive"
        case _:
            category = "Luxury"

    if category == "Low-cost":
        print("This product is budget-friendly.")
    elif category == "Moderate":
        print("This product offers good value for its price.")
    elif category == "Expensive":
        print("This product is relatively pricey.")
    else:
        print("This product is considered luxurious.")

product_price = 75
product(product_price)

# Output
# This product is relatively pricey.
				
			
				
					def describe_weather(condition):
    match condition.lower():
        case "sunny":
            if input("Is it hot outside? (yes/no): ").lower() == "yes":
                return "It's a hot and sunny day."
            else:
                return "It's a pleasant sunny day."

        case "cloudy":
            return "The sky is overcast with clouds."

        case "rainy":
            return "It's raining, don't forget your umbrella!"

        case _:
            return "Weather condition is unknown."

def main():
    weather_condition = input("Enter the current weather condition: ")
    description = describe_weather(weather_condition)
    print(description)

main()

# Input1
# sunny
# Input2
# no

# Output
# It's a pleasant sunny day.