How to use match-case

捕获
b is not defined

Please do not post screenshots or photos of your code and errors.

Please copy and paste them as text, and use the </> button to format them as code.

Your code works for me:


a = 1

match a:

    case b:

        print("ok")

And the output is “ok” as expected. What happens when you try?

I have thought some more about your question, and I wonder whether you

are surprised by the match statement


match a:

    case b:

        print("ok")

because you think this is equivalent to:


if a == b:

    print("ok")

like a C switch statement? But Python’s match statement is not like a C switch statement, it is like pattern-matching in Haskell.

Your match statement is closer to this:


try:

    b, = a

except TypeError:

    # Go on to the next case

else:

    print("ok")

You should read the tutorial for match:

and the rest of the documentation for it:

https://docs.python.org/3/reference/compound_stmts.html#the-match-statement