Companies Home Search Profile

Emulating switch/case Statements in Python

Focused View

Dan Bader

10:51

256 View
  • 03 Emulating Switch-Case Statements - part1.mp4
    01:20
  • 03 Emulating Switch-Case Statements - part2.mp4
    01:19
  • 03 Emulating Switch-Case Statements - part3.mp4
    03:17
  • 03 Emulating Switch-Case Statements - part4.mp4
    04:55
  • Description


    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.

    More details


    User Reviews
    Rating
    0
    0
    0
    0
    0
    average 0
    Total votes0
    Focused display
    Category

    Dan Bader is the owner and editor in chief of Real Python and the main developer of the realpython.com learning platform. Dan has been writing code for more than 20 years and holds a master’s degree in computer science. He’s the author of Python Tricks, a best selling programming book for intermediate Python developers.

    Hey, I’m Dan Bader and I help Python developers take their coding skills and productivity to the next level. I’m an independent software engineer, author, and speaker. I’ve been writing code for more than two decades—and I’d love to help you become a more proficient Python coder.

    Here’s where you can find me elsewhere on the web:

    I’ve also done some podcast interviews and other media appearances you can check out:

    Learn Python online: Python tutorials for developers of all skill levels, Python books and courses, Python news, code examples, articles, and more.
    • language english
    • Training sessions 4
    • duration 10:51
    • Release Date 2023/01/05