What is the Python equivalent for a case/switch statement?

This question already has an answer here:

  • Replacements for switch statement in Python? 44 answers

  • While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

    For example:

    # define the function blocks
    def zero():
        print "You typed zero.n"
    
    def sqr():
        print "n is a perfect squaren"
    
    def even():
        print "n is an even numbern"
    
    def prime():
        print "n is a prime numbern"
    
    # map the inputs to the function blocks
    options = {0 : zero,
               1 : sqr,
               4 : sqr,
               9 : sqr,
               2 : even,
               3 : prime,
               5 : prime,
               7 : prime,
    }
    

    Then the equivalent switch block is invoked:

    options[num]()
    

    This begins to fall apart if you heavily depend on fall through.


    The direct replacement is if / elif / else .

    However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

    链接地址: http://www.djcxy.com/p/42752.html

    上一篇: 由于Python没有switch语句,我应该使用什么?

    下一篇: 什么是case / switch语句的Python等价物?