Like in this question, I am trying to match an element in a list, and handle the cases accordingly. See the example below.
direct_payments = ["creditcard", "debitcard"]
on_credits = ["gift card", "rewards program"]
def print_payment_type(payment_type):
match payment_type:
case in direct_payments:
print("You paid directly!")
case in on_credits:
print("You paid on credits!")
print_payment_type("gift card")
I want this to print "You paid on credits". I am convinced that using structural pattern matching is the most readable option in my case. Is there any way to achieve this behaviour? I cannot use "gift card" | "rewards program", because I need to use the lists elsewhere.
caseneeds to a pattern (the feature is called structural pattern matching after all). So we cannot include a function there (e.g.case XX in direct_credits.) [Thanks to matszwecja for this clarification.]The cases are generated by the
matchstatement. So we cannot do thiscase in direct_payments:.I could think of an application of
caselike this:However, I do not understand why you would prefer
caseoverif/ elif/else. You could combine your requirements easily usingand/or. Anything that you want to do usingmatch-case should be easily doable usingelif` conditions.This link should be where you can get more examples of using case.
EDIT: gimix has a better answer.