[英]How can I do if elif and else in case?
我正在尝试制作西班牙语语音助手。 我不知道如何用if
、 elif
和else
创建一个案例。
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.