Search code examples
pythonconditional-statementsvlc

Python, if a or b and c , not working as expected


I'm stuck with an issue that feels so simple yet I can't figure it out.

The following example returns 'else' as expected:

a, b, c = False, False, True
if a or b and c:
    print('if')
else:
    print('else')

now, if I apply the same logic to my project as done below:

import time, vlc

def play_sound(path):
    _ = vlc.MediaPlayer(path)
    _.play()

def check_commands(audio_capture):
if 'who' or 'what' in audio_capture and "are you" in audio_capture:
    play_sound("ResponseToCommands/response_A.mp3")
    time.sleep(2.2)

elif audio_capture == "are you ready":
    play_sound("ResponseToCommands/response_B.mp3")

check_commands('are you ready')
time.sleep(5) # optional
check_commands('what are you')

I would expect the same results. However, I keep getting response_A.mp3 instead of first response_B and then response_A.

Any suggestion would be appreciated.


Solution

  • Your condition is parsed the same as

    if 'who' or ('what' in audio_capture and "are you" in audio_capture):
    

    'who' is a truthy value, so the entire condition is true without ever needing to check for values in audio_capture.

    What you wanted was

    if ('who' in audio_capture or 'what' in audio_capture) and "are you" in audio_capture:
    

    in does not "distribute" over or like multiplication distributes over addition.