繁体   English   中英

如果 elif 和 else 以防万一,我该怎么办?

[英]How can I do if elif and else in case?

我正在尝试制作西班牙语语音助手。 我不知道如何用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)

看起来您的代码中有缩进错误。 python 中没有开关,因此您必须使用 if-elif-else 来执行此操作。 如果你愿意,你可以创建一个 function 作为开关盒。 像这样:

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)

IndentationError:尝试时需要缩进块

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

要在 python 中模拟 switch 语句,您可以像这样定义一个帮助器 function:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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