【问题标题】:Switch-case statement in PythonPython 中的 switch-case 语句
【发布时间】:2021-06-13 00:48:24
【问题描述】:

我厌倦了尝试制作一个让我从字典键中进行选择的菜单,并且在每个值中我都可以选择。我发现我可以使用字典和 get() 方法,它工作正常,但我应该在 get() 之后使用 if else 语句来执行一个回答用户选择的函数。我可以做得更好吗?也许在键值内使用 lambda?

def menu():
        print("Welcome to Our Website")
        choises={
            1:"Login" ,
            2:"Register",
        }
        for i in choises.keys(): # Loop to print all Choises and key of choise ! 
            print(f"{i} - {choises[i]}")
        arg=int(input("Pleasse Chose : "))
        R=choises.get(arg,-1)
        while R==-1:
            print("\n Wrong Choise ! Try again ....\n")
            menu()
        else:
            print(f"You Chosed {R}")
            if R==1:
                login()
            if R==2:
                register()


def register():
    print("Registration Section")
def login():
    print("Login Section")
    
    
menu()   

【问题讨论】:

    标签: python menu switch-statement


    【解决方案1】:

    您可以使用以下函数定义模拟 switch 语句:

    def switch(v): yield lambda *c: v in c
    

    你可以在 C 风格中使用它:

    x = 3
    for case in switch(x):
    
        if case(1):
            # do something
            break
    
        if case(2,4):
            # do some other thing
            break
    
        if case(3):
            # do something else
            break
    
    else:
        # deal with other values of x
    

    或者您可以使用 if/elif/else 模式而不使用中断:

    x = 3
    for case in switch(x):
    
        if case(1):
            # do something
    
        elif case(2,4):
            # do some other thing
    
        elif case(3):
            # do something else
    
        else:
            # deal with other values of x
    

    对于函数调度来说特别有表现力

    functionKey = 'f2'
    for case in switch(functionKey):
        if case('f1'): return findPerson()
        if case('f2'): return editAccount()
        if case('f3'): return saveChanges() 
    

    【讨论】: