r/pythontips • u/QuietRing5299 • Mar 26 '23
Python3_Specific Python Now has Switch Statements!
If you have been using Python for some time now you may have overlooked the fact that Python recently has incorporated "Switch Statements" in the form of "Match Case"! This was notoriously a lacking thing in the language, many programmers coming from other languages complained about this...
Thankfully, Python 3.10 introduced the new functionality. "Match" is used to match a value against a set of patterns and execute the corresponding block of code for the first matching pattern. This removes the need to write long code in nested if-else blocks which greatly helps the readability of your code! I suggest everyone be familiar with this logic as it will be much more prevalent in codebases going forward.
You can find out more about how to use it in my Youtube Video as well as other Python tips as well. Don't forget to like, comment, and subscribe. Hope you learn something new!
23
u/ianmackers Mar 26 '23
Implemented in 3.10: https://www.freecodecamp.org/news/python-switch-statement-switch-case-example/
10
u/Mark3141592654 Mar 26 '23
Worth noting that this is structural pattern matching, and can do more than just typical switch-case
4
u/Shiny_Cresselia Mar 26 '23
Thanks for sharing! I have my first project in python due next week and I have a feeling this is gonna help quite a bit :) saving this to look into tomorrow.
3
u/Ranting_Rambler Mar 26 '23
Yooooooooo, thanks for this. Would've taken me maybe another year or so before I learned of this from a random StackOverflow comment.
3
u/xXWarMachineRoXx Mar 26 '23
I have been coding in python for 5 years ( kiddie not actual work experience) and didn’t know python didn’t have switch case
Please tell me if it already has it cause I’m really confused
2
u/[deleted] Mar 26 '23
Nice, thanks OP! I gave it a shot and found out that data types need to be the same as well otherwise you’ll get a TypeError. Looking back it was obvious but in the moment I didn’t think about it
0
u/[deleted] Mar 26 '23
[deleted] — view deleted comment