Click for All Topics
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.
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!
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.
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.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!
match-case
work?let’s break it down step by step:
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!
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
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.
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India