Python Elif 语句不执行第四个条件

问题描述

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

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

我尝试用第四个 Elif 替换第三个 Elif,但它仍然在第三个位置执行 Elif。

这是我的代码...... run() 函数中存在问题

# 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()

解决方法

您的条件并不像您认为的那样工作:(('who' or 'what') and 'is') or 'wikipedia' in command: 应该是 ((('who' in command) or ('what' in command)) and 'is' in command) or 'wikipedia' in command 等等。 (('who' or 'what') and 'is') or 'wikipedia' 等价于 is,因为布尔运算符在 Python 中的实现方式,因此您编写的条件等价于 'is' in command

Python reference

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