【问题标题】:Python Elif statement not executing fourth conditionPython Elif 语句未执行第四个条件
【发布时间】:2021-05-30 08:42:28
【问题描述】:

我正在用 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()

【问题讨论】:

  • 不确定这是否只是问题或代码中的问题。但是 if ... elif ... 与您的 def run() 处于同一缩进级别,因此它们不是该功能的一部分
  • @derpirscher 抱歉格式化,这是在发布问题时发生的。 if、elif 和 else 语句在我的代码编辑器中的 def run() 内完美对齐。

标签: if-statement conditional-statements desktop assistant


【解决方案1】:

您的条件不像您想的那样工作:(('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 而不是''。)

【讨论】:

  • 非常感谢您的回答,现在工作正常。而且我之前忘记提到 defanything_else() 存在问题。在此功能中,仅当条件有效时才有效,否则无效。提前致谢
  • 并且每当 def take_command() 函数遇到异常并再次运行 def take_command 时,都会发生此属性错误。 AttributeError: 'NoneType' 对象没有属性 'lower'。但我不能排除 lower() 因为它确实需要
  • 如果我的提问正确 - 你在 except Exception as e: 中缺少 return。因此,它再次运行tk_command,但不返回结果,即返回None
  • @SamratGupta anything_else() 中的条件与run() 中的问题相同。 if 'no' or 'nope' or 'nah' or 'na' in command 应该是 if 'no' in command or 'nope' in command or 'nah' in command or 'na' in command。顺便说一句,您不需要同时检查nonope,因为如果命令中不包含no,则不能包含nopenanah 相同
  • 非常感谢,它确实解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多