I dont know why but this is an extremely useful function yet extremely under documented/used in python help forums and websites. I mean w3schools.com has absolutely no mention of it. Many other programming languages use this only with the "switch-case" syntax and python implemented it in 3.10. When I found this out last week I immediately found places where I can use it and it looks so much cleaner if-elif statements and is so readable. However the lack of documentation makes it a bit hard to find some of its details. Its probably all in the actual python docs but I find those hard to understand sometimes so I like to reference difference websites and help forums. Heres a quick example if you want to get started using and Ill point out some of the hidden details.
Note: One this I would call a downfall is that it doesnt recognize the logical operator keywords (and, or) but you can use the symbol shortcut (| for OR). I cant understand why they would allow that but not the actual keywords especially considering python tends to use the full keywords more so than other languages. Anyway hopefully they'll update that in a later version. And Im not sure about others like (IS, NOT, IN) and comparison operators (< , >, <=, >=) but I did notice somebody said in a different forum that you can use this syntax "case in ['x', 'y', 'z']" but that didnt work for me. It didnt let me use the in operator at all. I had to go with the | (or) rout. Maybe they've changed it from an earlier version. In any case its a great thing to know about if you ask me.
Python:
print("""
1.) Do this
2.) Do that
3.) Exit
or press X to QUIT""")
user_selection = input("Enter a selection: ")
match user_selection.lower():
case '1':
print("Do this")
case '2':
print("Do that")
case '3' | 'x':
print("Thanks. See you later!")
exit()
case _:
# This is the syntax for a non-match
print("Invalid selection")
Note: One this I would call a downfall is that it doesnt recognize the logical operator keywords (and, or) but you can use the symbol shortcut (| for OR). I cant understand why they would allow that but not the actual keywords especially considering python tends to use the full keywords more so than other languages. Anyway hopefully they'll update that in a later version. And Im not sure about others like (IS, NOT, IN) and comparison operators (< , >, <=, >=) but I did notice somebody said in a different forum that you can use this syntax "case in ['x', 'y', 'z']" but that didnt work for me. It didnt let me use the in operator at all. I had to go with the | (or) rout. Maybe they've changed it from an earlier version. In any case its a great thing to know about if you ask me.
Last edited: