On-screen text
IT
Switch-Case In Python
@ITCHALLENGES
SWIPE >>>
As you may already know, Python doesn't have an in-built switch statement like other programming languages.
@ITCHALLENGES
SWIPE >>>
The Pythonic way to implement switch statements is to use dictionary mappings...
@ITCHALLENGES
SWIPE >>>
def months(number):
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
# Returns the name of the month, but if the
# number isn't found it returns "Invalid month"
return switcher.get(number, "Invalid month")
@ITCHALLENGES
SWIPE >>>
However, from Python 3.10, a new feature called Structural Pattern Matching has been added. Let's see how you can use it!
@ITCHALLENGES
SWIPE >>>
def days(number):
match number:
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursday"
case 5:
return "Friday"
case 6:
return "Saturday"
case 7:
return "Sunday"
@ITCHALLENGES
SWIPE >>>
With the match-case, you can evaluate the subject in the match statement and compare it with each pattern in a case statement.
@ITCHALLENGES
SWIPE >>>
If an exact match is not confirmed, you can use an optional wildcard _ as the matching case:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case _:
return "Something's wrong"
@ITCHALLENGES
SWIPE >>>
You can also combine several literals in a single pattern using | ("or"):
def http_error(status):
match status:
case 401 | 403 | 404:
return "Not allowed"
@ITCHALLENGES
SWIPE >>>
IT Challenges
@itchallenges
SQL & NoSQL Big Linux Java
Comparison Cheat Sheet Challenge
Top VSCode Don't Write Python
Extensions Code All Day Challenge
Speed Test 7 Challenge C
With Python Websites Challenge
Windows Improve Your C++
Coming Soon Typing Speed Challenge
Was this post useful to you? Visit our profile and check out more from us!
@ITCHALLENGES
SWIPE >>>