Élio Pereira
Élio Pereira

Reputation: 221

Defining a match-case statement with the same instruction for two different cases in Python

I would like to create a match-case statement in Python in which two cases do the same instruction. For instance, if Python behaved like C++, according to this Stack Overflow question, I would write the match-case statement as:

        match x:
            case 1:
            case 2:
                # Some code
                break
            case 3:
                # Some code
                break

The code however does not work, showing that the match-case statement needs to be written in a different way in Python. What is this way?

Upvotes: 3

Views: 3471

Answers (2)

dev_light
dev_light

Reputation: 3919

Just my own 2 cents, according to the official Python 3 tutorial, in a match-case you can combine several literals in a single pattern using | (“or”). In your case, it would look like this:

def x(num):
    match num:
        case 1 | 2:
            # your codes...
        case 3:
            # your codes...
        case _:
            # This is the wildcard pattern and it never fails to match.


# call your function
x(6)    # This will result in the wildcard pattern since case 6 isn't specified.

Hope this helps someone else out there!

Upvotes: 0

rici
rici

Reputation: 241731

match x:
    case 1 | 2:
        # Some code
    case 3:
        # Some code

Python match clauses don't fall through, so you can't concatenate them as in C and you don't use break at the end of the clause.

The "OR pattern" (as shown, where | means "or") can be used with subpatterns which bind variables, but all the subpatterns need to bind the same variables.

Upvotes: 7

Related Questions