如果是elif和else我该怎么办?

2024-09-30 12:12:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个西班牙语语音助手。我不知道如何用ifelifelse创建一个案例

    if texto == nada:
      engine.say("Ok estare para  ti cuando me necesites")
      engine.runAndWait()
      
    elif texto == notenecesito:
      engine.say("Ok estare para  ti cuando me necesites")
      engine.runAndWait()
    elif texto == lahora:
      engine.say("La hora es"+ current_time)
      engine.runAndWait()
      print(Fore.RED+current_time)
    else:
      engine.say("buscando " + texto ,"Abriendo el navegador")
      engine.runAndWait()
      webbrowser.open("https://www.google.com/search?q="+texto)

Tags: iftiokcurrentelseenginemesay
3条回答

看起来代码中有缩进错误。python中没有开关,因此必须使用if-elif-else。如果需要,您可以创建一个函数,该函数将用作开关盒。像这样:

def switch(texto):
    if texto == "nada":
        engine.say("Ok estare para  ti cuando me necesites")
        engine.runAndWait()
      
    elif texto == "notenecesito":
        engine.say("Ok estare para  ti cuando me necesites")
        engine.runAndWait()
    elif texto == "lahora":
        engine.say("La hora es"+ current_time)
        engine.runAndWait()
        print(Fore.RED+current_time)
    else:
        engine.say("buscando " + texto ,"Abriendo el navegador")
        engine.runAndWait()
        webbrowser.open("https://www.google.com/search?q="+texto)

或者您可以使用字典映射,如下所示:

def switch(texto):
    switcher = {"nada":"Ok estare para  ti cuando me necesites", "notenecesito":"Ok estare para  ti cuando me necesites", .......}
    return switcher.get(texto, None)

缩进错误:尝试时应为缩进块

def switch(texto):
    if texto == "nada":
        engine.say("Ok estare para  ti cuando me necesites")
        engine.runAndWait()

要在python中模拟switch语句,可以定义如下所示的助手函数:

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

并以类似C的方式使用它:

for case in switch(texto):

    if case(nada, notenecesito):
       engine.say("Ok estare para ti cuando me necesites")
       engine.runAndWait()
       break
  
    if case(lahora):
       engine.say("La hora es"+ current_time)
       engine.runAndWait()
       print(Fore.RED+current_time)
       break
else:
    engine.say("buscando " + texto ,"Abriendo el navegador")
    engine.runAndWait()
    webbrowser.open("https://www.google.com/search?q="+texto)

相关问题 更多 >

    热门问题