在python中实现switch语句的最佳方法是什么?

时间:2017-07-04 08:45:53

标签: python switch-statement

我通过各种书籍和博客阅读,得出结论,这是最好的。我仍然不知道在python中实现switch函数是否更好。我想编辑这个问题,因为有人将其标记为重复。我想用一个正确的答案来回答这个问题,任何人都可以搜索并找到一个在python中实现switch语句的最佳答案。这将阻止用户搜索许多博客,论坛或许多书籍以找到答案。按照Pythonic的方式,每个问题都有一个最好的答案。

class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''
    print "exception occured"
    if (LookupError =='001'):
        print "There is something to fix"


def PrintBlue():
    print (" You chose Blue!\r\n")

def PrintRed():
    print (" You chose Red!\r\n")

def PrintOrange():
    print (" You chose Orange!\r\n")

def PrintYellow():
    print (" You chose Yellow!\r\n")

#Let's create a dictionary with unique key

ColorSelect = {
    0:PrintBlue,
    1:PrintRed,
    2:PrintOrange,
    3:PrintYellow
    }



Selection = 0

while (True):
    print ("0.Blue")
    print ("1.Red")
    print ("2.Orange")
    print ("3.Yellow")
    try:
        Selection = int(input("Select a color option: "))
        x=0
        if ( Selection < 0) or (Selection > 3):
            raise MyAppLookupError(" Enter a number >=0 and <4)")
    except MyAppLookupError as er:
            print er
    else:
        ColorSelect[Selection]() # Run the function inside dictionary as well

    finally:
       pass

还有另一种方法是使用if-then-else语句

0 个答案:

没有答案