Emulating switch/case Statements in Python
Dan Bader
4 Lessons
10m
intermediate
python
Python doesnβt have switch/case statements so itβs often necessary to write long if/elif/else chains as a workaround. Hereβs a little trick you can use to emulate switch/case statements in Python using dictionaries and first-class functions.
Basically weβre using Python dictionaries as a lookup table to replace a nested βif elif elseβ statement with a cleaner and more maintainable implementation.
In some cases this can be faster than if-then-else chains and easier to maintain, too. To see if this method is right for you watch the video tutorial and learn how to apply this technique to write nice and clean Python.
Emulating switch/case Statements in Python
4 Lessons 10m
About Dan Bader
Dan is the Chief Python Nut at Real Python. He helps Python developers take their coding skills to the next level with Python tutorials, books, and online training.
Β» More about Dan

