Search code examples
pythonpython-3.xconditional-statementsvoice-recognition

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


Hello everyone ı wonder what else we can use instead of elif, if , else statements? or how can ı change given if , elif , else statement to any other method..

Assume that ı have voice assistant like this;

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} ")

so I wonder, What else do I try instead of elif? Can you please explain to me? ı know elif , if , and else statements.In this case if I want to write other command ı have to write;

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

elif command in "": 
    """"

and so on.. so that rows are too many can ı make the codes more shorter instead of elif statements? or should i continue like this?


Solution

  • You can use dictionary. Here is complete example

    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)