[英]How can I do if elif and else in case?
I am trying to make a spanish voice assistant.我正在尝试制作西班牙语语音助手。 I don't know how create a case with if
, elif
and else
.我不知道如何用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)
Looks like you have indentation error in your code.看起来您的代码中有缩进错误。 There's no switch in python so you have to use if-elif-else to do so. python 中没有开关,因此您必须使用 if-elif-else 来执行此操作。 If you want you can create a function which will work as switch case.如果你愿意,你可以创建一个 function 作为开关盒。 Like this:像这样:
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)
or you can use dictionary mapping like this:或者您可以像这样使用字典映射:
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: expected an indented block when try IndentationError:尝试时需要缩进块
def switch(texto):
if texto == "nada":
engine.say("Ok estare para ti cuando me necesites")
engine.runAndWait()
To simulate a switch statement in python, you can define a helper function like this:要在 python 中模拟 switch 语句,您可以像这样定义一个帮助器 function:
def switch(v): yield lambda *c: v in c
And use it in a C-like style:并以类似 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.