You can define a default case in Python. For this you use a wild card (_). The following code demonstrates it:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
case _:
print("not matched")
Answer from Prince Hamza on Stack OverflowIs it "right" to use the match/case statement rather than if/else when you just want to check certain conditions?
Should I use match case instead of if else
Match/case syntax
Anyone used match case yet?
Videos
You can define a default case in Python. For this you use a wild card (_). The following code demonstrates it:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
case _:
print("not matched")
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
cf: https://docs.python.org/3.10/whatsnew/3.10.html#syntax-and-operations
I can't say I fully understand the match/case statement yet, but I know a part of it involves more than just simple pattern matching. I know that the expression in the match statement, for example, actually runs and creates a result, such as an object if it's a call to a class.
So I'm wondering, if I don't want to do all that and just want to use it as a cleaner version of if/else, is this considered Pythonic, or is it overkill?
For example:
if some_value == True and some_other == 1:
do something
elif some_value == False and some_other == 1:
do something else
etc etc etcor:
match (some_value, some_other):
case (True, 1):
do something
case (False, 1):
do something else
etc etc etcFirst off, I *think* I'm getting the syntax correct! Second, I'm not actually creating any values with the expressions, so it feels like a glorified if/else construct, just cleaner looking.
Is this a valid use of match/case?
Thanks!
I have learned about match case after learning if else and i found that match case are faster than if else so should I replace all if else statement with math case