If statement Python Elif语句未执行第四个条件

If statement Python Elif语句未执行第四个条件,if-statement,conditional-statements,desktop,assistant,If Statement,Conditional Statements,Desktop,Assistant,我正在用python构建一个桌面助手 if条件和前两个Elif条件仅在文件中起作用,但当我尝试调用第四个Elif条件时,无论我如何更改条件,它都会自动调用第三个Elif条件 我试着用第四个Elif替换第三个Elif,但仍然是在第三个位置执行Elif 这是我的密码。。。。。。run()函数中存在问题 你的条件不符合你的想法:(('who'或'what')和'is')或'wikipedia'在命令中:应该是(('who'在命令中)或('what'在命令中))和'is'在命令中)或'wikipedia

我正在用python构建一个桌面助手

if条件和前两个Elif条件仅在文件中起作用,但当我尝试调用第四个Elif条件时,无论我如何更改条件,它都会自动调用第三个Elif条件

我试着用第四个Elif替换第三个Elif,但仍然是在第三个位置执行Elif

这是我的密码。。。。。。run()函数中存在问题


你的条件不符合你的想法:
(('who'或'what')和'is')或'wikipedia'在命令中:
应该是
(('who'在命令中)或('what'在命令中))和'is'在命令中)或'wikipedia'在命令中
等等。
(('who'或'what')和'is')或'wikipedia'
相当于
is
,因为在Python中布尔运算符的实现方式,所以您编写的条件相当于命令中的
'is

见:


请注意,
以及
都没有限制它们返回的值和类型为
False
True
,而是返回最后计算的参数。这有时很有用,例如,如果
s
是一个字符串,如果该字符串为空,则应将其替换为默认值,则表达式
s或“foo”将生成所需的值。由于
not
必须创建一个新值,因此无论其参数的类型如何,它都会返回一个布尔值(例如,
not'foo'
生成
False
,而不是
'

不确定这是问题还是代码中的问题。但是
如果
<代码>elif
。。。与您的
def run()
处于相同的缩进级别,因此它们不是缩进级别的一部分function@derpirscher很抱歉设置了格式,这是在发布问题时发生的。在我的代码编辑器中,如果、elif和else语句在def run()中完全对齐。非常感谢您的回答,它现在工作得很好。而且我之前忘了提到def中还有其他问题()。在该功能中,仅当条件起作用时,其他情况下均不起作用。非常感谢,每当def take_命令()函数遇到异常并再次运行def take_命令时,就会发生此属性错误。AttributeError:“NoneType”对象没有属性“lower”。但我不能排除lower(),因为如果我正确回答了您的问题,确实需要它-您在
中缺少
return
,例外情况为e:
。因此,它再次运行
tk_命令
,但不返回结果,即返回
None
@SamratGupta
anythis()
中的条件与
run()
中的条件具有相同的问题
如果命令中的'no'或'nope'或'nah'或'na',
应为
如果命令中的'no'或'nope'或'nah'或命令中的'na'。顺便说一句,您不需要同时检查
no
nope
,因为如果
no
未包含在命令中,
nope
不能被删除。同样的
na
nah
非常感谢,它确实解决了我的问题。
# region                                                                            Importing Modules
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import webbrowser
# endregion

gender=0
rate = 190
listener = sr.Recognizer()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[gender].id)

def speak(text):
    engine.setProperty('rate', rate)   
    engine.setProperty('voice', voices[gender].id)
    engine.say(text)
    engine.runAndWait()

def tk_command():
    with sr.Microphone() as source:
        print("listening...")
        listener.adjust_for_ambient_noise(source)
        voice = listener.listen(source)
        try:
            command = listener.recognize_google(voice, language="en-in")
            command=str(command)
            return command
        except Exception as e:
            speak("Didn't hear anything, try again.")
            tk_command()

def hotword():
    global gender
    command = tk_command()
    if 'jarvis' in command.lower():
        gender=1
        speak("Jarves, hey buddy. You're up.")
        gender=0
        speak('Well, I am here to assist')
        print (command)
        run()
    elif 'friday' in command.lower():
        gender=0
        speak("Hey Friday, it's your call")
        gender=1
        speak('Ok, how can I assist')
        print (command)
        run()

def anything_else():                                                #### Check if this works ####
    speak("Any other service I can do ?")
    command=tk_command()
    command.lower()
    if 'no' or 'nope' or 'nah' or 'na' in command:
        speak("Ok. Happy to help.")
        print(command)
        hotword()
    elif command == 'yes' or command == 'yeah' or command == 'yup':
            speak("Ok. Just ask me.")
            run()
    else:
        speak("Sure...")
        run(command, True)


def run(command=None, check=False):
    global rate
    # region                                                                        Taking command input
    if check == False:
        command = tk_command()
    command = command.lower()
    command = command.replace('friday', '')
    command = command.replace('Jarvis', '')
    # endregion

''' Functioning of various commands are describes below
     as multiple elif statements '''

if ('play' or 'search') and 'youtube' in command and 'google' not in command:   # Play or search on youtube
    song = command.replace('play', '')
    song = song.replace('youtube', '')
    song = song.replace('on', '')
    song = song.replace('for', '')
    speak('Playing.'+ song)
    pywhatkit.playonyt(song)

elif ('send' or 'message') and 'whatsapp' in command:                           # Sending a Whatsapp message
    if 'to' not in command:                 # Check if phone number is input
        speak('''Please say the command with a phone number or a contact name.
             To save a new contact say, Save... your phone number... 
                as... name of the recepient.''')
    else:                                   # Else Send the message
        command = command.replace('send', '')
        command = command.replace('whatsapp', '')
        command = command.replace('message', '')
        command = command.replace('to', '')
        command = command.replace('on', '')
        try:
            number = int(command.replace(' ',''))
            speak("Sure, what's the message.")
            message = tk_command()
            pywhatkit.sendwhatmsg_instantly(f"+91{number}", message)
        except Exception as e:
            speak('Invalid number or contact, please try again.')
            print (command)
            run()

elif 'time' in command:                                                         # Asking what time is it
    time = datetime.datetime.now().strftime('%I:%M:%S %p')
    speak('Right now, its, '+ time)

elif 'search google for' or ('search' and 'on google') in command:              # Searches anything on google
    print('Google Search')
    command=command.replace('search google for', '')
    command=command.replace('search', '')
    command=command.replace('on google', '')
    command=command.replace(' ', '+')
    pywhatkit.search(command)
    
elif (('who' or 'what') and 'is') or 'wikipedia' in command:                    # Searches wikipedia for anything or anyone
    print(command)
    print('Wikipedia Search')
    lines = 1
    if 'explain' in command:
        lines = 3
        command = command.replace('explain', '')
    command = command.replace('who', '')
    command = command.replace('what', '')
    command = command.replace('is', '')
    info = pywhatkit.info(command, lines)
    rate -= 20
    speak(info)
    rate += 20

else:                                                                           # Exits the program
    speak('Exiting the program.')
    sys.exit()

anything_else()


hotword()