简体   繁体   中英

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. Can I do it better? Maybe using a lambda inside the key value?

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:

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

You can use it in C-style:

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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