Control Flow and Logic
18 min read
Match Case
Match Case
Sometimes you need to compare one value with many possible choices.
For example:
- If the user enters
1, show Home - If the user enters
2, show Profile - If the user enters
3, show Settings
Python has a clean way to do this called match case.
What Is Match Case?
match case checks one value and compares it with different options.
It is often easier to read than many if elif else lines.
Basic Example
day = "Monday"
match day:
case "Monday":
print("Start of the week")
case "Friday":
print("Weekend is near")
case _:
print("Regular day")
How It Works
Let’s break it down:
- Python checks the value of
day - It compares it with each
case - If it finds a match, it runs that block
_means default if nothing matches
Why Use Match Case?
Use match case when one value can have many clear options.
Examples:
- Menu choices
- Days of the week
- User commands
- Status messages
Another Example
number = 2
match number:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case _:
print("Unknown number")
Code Along
choice = "yes"
match choice:
case "yes":
print("You selected yes")
case "no":
print("You selected no")
case _:
print("Invalid choice")
Mini Challenge
Build a menu app.
Steps:
- Ask the user to enter a number
- If they enter
1, print:
Home - If they enter
2, print:
Profile - If they enter
3, print:
Settings - For anything else, print:
Invalid option
Real World Use Case
Apps use match case for menus, commands, status checks, and handling different user selections.
Quiz
- What does
match casedo? - When is it better than many
if elif elselines? - What does
_mean? - Can
match casecheck numbers and text?
Assignment
Create a day checker.
- Ask the user to enter a day name
- Show a different message for Monday, Friday, and Sunday
- Show
Unknown dayfor anything else
Summary
You learned how match case helps Python compare one value with many possible choices in a clean and readable way.