簡體   English   中英

我還能用什么來代替 python 中的 elif、if、else 語句?

[英]What else can I use instead of elif, if , else statements in python?

大家好,我想知道我們還可以使用什么來代替 elif、if、else 語句? 或者如何將給定的 if 、 elif 、 else 語句更改為任何其他方法..

假設我有這樣的語音助手;

webb = ["open web browser","web browser", "open browser"]
thkns = ["thank you","thank you so much", "thanks"]
fav_web = ["open my favourite web site","favourite web site","my best web site"]
hwaru = ["how are you", "what's up", "how is going"]
thtime = ["whats the time" , "the time", "time"]

def assistant(command):
    if command in webb:
        talkMe("Opening your web browser")
        webbrowser.open("https://www.google.com.tr")

    elif command in thkns: 
        talkMe("You are welcome")


    elif command in fav_web:
        talkMe("Opening your site")
        webbrowser.open("www.stackoverflow.com")

    elif command in hwaru: 
        msg = ["ı am good, you?", "good", "not bad"]
        talkMe(random.choice(msg))


    elif command in thtime:
        strTime = datetime.datetime.now().strftime("%H:%M:%S")
        talkMe(f"The time is {strTime} ")

所以我想知道,除了 elif,我還能嘗試什么? 你能給我解釋一下嗎? 我知道 elif 、 if 和 else 語句。在這種情況下,如果我想寫其他命令,我必須寫;

elif command in "":
    talkMe("")
    do some """

elif command in "": 
    """"

等等..所以行太多可以讓代碼更短而不是 elif 語句嗎? 還是我應該繼續這樣?

看起來你可以使用字典。

d = {'Hello Google': obj1, 'open my favourite web site': obj2}

您可以使用字典。 這是完整的例子

def switch_demo(argument):
    switcher = {
        "open web browser": "Opening your web browser",
        "web browser": "Opening your web browser",
        "open browser": "Opening your web browser",
        "thank you": "You are welcome",
        "thank you so much": "You are welcome",
        "thanks": "You are welcome"
    }
    print(switcher.get(argument, "Invalid Command"))

command = "thank you"
switch_demo(command)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM