请帮助我解决 python 中带有 "and" 的 if 语句中的问题
Please help me to solve the problem in if statement with "and" in python
我正在尝试做一个语音助手。它有很多问题。但是这次我在 if 语句中遇到了一个非常奇怪的问题。我的代码:
greeting() # greeting mesaage
ear = listen() # listen my voice stored in ear variable
mind = str(recognise(ear)) #recogniser convert it in text by help of google and store in mind variable
if "what"and"about"and"you" in mind:
speak(" i am also fine!")
speak("what can i do for you?")
elif "information" in mind:
speak("what you want to know from me, sir!")
每当我说出“what”或“about”或“you”中的一个词时,即使带有“information”,它也会执行 if 语句而不是 elif 语句。虽然根据我的理解,只要这 3 个单词在同一个字符串中,它就必须从 if 语句传递。
所以我很困惑代码中的错误是什么。
这一行-
if "what"and"about"and"you" in mind:
speak(" i am also fine!")
speak("what can i do for you?")
不是你想的那样。您需要为每个字符串添加 in
-
if "what" in mind and "about" in mind and "you" in mind:
speak(" i am also fine!")
speak("what can i do for you?")
基本上,在前面的 if 语句中,语句转换为 - if true and true and 'you' in mind
,这与您想要的逻辑完全不同。
根据你的单词列表有多大,你可以花点时间做这样的事情:
words = ["what", "about", "you"]
mind = "That's what I like about you"
if [word for word in words if word in mind]:
speak(" i am also fine!")
speak("what can i do for you?")
我正在尝试做一个语音助手。它有很多问题。但是这次我在 if 语句中遇到了一个非常奇怪的问题。我的代码:
greeting() # greeting mesaage
ear = listen() # listen my voice stored in ear variable
mind = str(recognise(ear)) #recogniser convert it in text by help of google and store in mind variable
if "what"and"about"and"you" in mind:
speak(" i am also fine!")
speak("what can i do for you?")
elif "information" in mind:
speak("what you want to know from me, sir!")
每当我说出“what”或“about”或“you”中的一个词时,即使带有“information”,它也会执行 if 语句而不是 elif 语句。虽然根据我的理解,只要这 3 个单词在同一个字符串中,它就必须从 if 语句传递。 所以我很困惑代码中的错误是什么。
这一行-
if "what"and"about"and"you" in mind:
speak(" i am also fine!")
speak("what can i do for you?")
不是你想的那样。您需要为每个字符串添加 in
-
if "what" in mind and "about" in mind and "you" in mind:
speak(" i am also fine!")
speak("what can i do for you?")
基本上,在前面的 if 语句中,语句转换为 - if true and true and 'you' in mind
,这与您想要的逻辑完全不同。
根据你的单词列表有多大,你可以花点时间做这样的事情:
words = ["what", "about", "you"]
mind = "That's what I like about you"
if [word for word in words if word in mind]:
speak(" i am also fine!")
speak("what can i do for you?")