简体   繁体   English

Python 中的 switch-case 语句

[英]Switch-case statement in Python

I'm tired of trying to make a menu that let's me choose from a dictionary keys and in every value I have the choice.我厌倦了尝试制作一个让我从字典键中进行选择的菜单,并且在每个值中我都可以选择。 I found that I can use dictionary and get() method, it's working fine, but I should use if else statement after get() to execute a function that answers the user choice.我发现我可以使用字典和 get() 方法,它工作正常,但我应该在 get() 之后使用 if else 语句来执行回答用户选择的 function。 Can I do it better?我可以做得更好吗? Maybe using a lambda inside the key value?也许在键值内使用 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()   

you can simulate a switch statement using the following function definition:您可以使用以下 function 定义模拟 switch 语句:

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

You can use it in C-style:您可以在 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

Or you can use if/elif/else patterns without the breaks:或者您可以使用 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

It can be particularly expressive for function dispatch它对于 function 调度特别有表现力

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM