'Conditional statement inside a match case
Is it possible to have a conditional statement as a case for a match statement in Python?
Working something like this:
test = 'Aston Martin'
makes = ['Aston Martin', 'Bentley']
match test:
case if test in makes:
print(True)
case _:
print(False)
I know that match/case is not looking for something with boolean value True, but it seems like this would be useful to have for scaling things.
I tried to do it as a function so you can return the exact match:
test = 'Aston Martin'
makes = ['Aston Martin', 'Bentley']
def return_bool(item, lists):
if item in lists:
return item
else:
return 'notmatching'
match test:
case return_bool(test, makes):
print(True)
case _:
print(False)
This also didn't work. I think that it is expecting a format output, like - str(x)
I'm sorry if my explanation/vocabulary isn't right, please correct me as I am learning as I'm going along.
Solution 1:[1]
As the comments point out, the code you provided does seem like a better fit for if/elif, however it can be accomplished because match supports so-called "guard clauses".
test = 'Aston Martin'
makes = ['Aston Martin', 'Bentley']
match test:
case test if test in makes:
print(True)
case _:
print(False)
This works even in cases where makes is not a fixed sequence. If makes is really just a stand-in for a fixed sequence, then you could also use
test = 'Aston Martin'
match test:
case 'Aston Martin' | 'Bentley':
print(True)
case _:
print(False)
Note that you cannot do this
test = 'Aston Martin'
makes = ['Aston Martin', 'Bentley']
match test:
case makes:
print(True)
case _:
print(False)
as this will simply always match the first case, overwriting makes with test.
Solution 2:[2]
Use instead: if elif
Read to learn about match: PEP
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ROFLMAO |
