簡體   English   中英

Python 中的 switch-case 語句

[英]Switch-case statement in Python

我厭倦了嘗試制作一個讓我從字典鍵中進行選擇的菜單,並且在每個值中我都可以選擇。 我發現我可以使用字典和 get() 方法,它工作正常,但我應該在 get() 之后使用 if else 語句來執行回答用戶選擇的 function。 我可以做得更好嗎? 也許在鍵值內使用 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()   

您可以使用以下 function 定義模擬 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

它對於 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