0

This is my code:

import keyboard as kb

def key_selected():
    if kb.is_pressed('shift+s+down'):
        return 'True1' 
    
    elif kb.is_pressed('shift+s+right+down'):
        return 'True2'
    
    else:
        return 'NOTHING' 

while True:
    x = key_selected()
    print(x)

It returns True1 even when I press 'shift+s+right+down'. How can resolve this?

Saat
  • 15
  • 4
  • 3
    This may be a simple logic problem. If the `shift` and `s` and `right` and `down` keys are pressed, then it is _also_ true that the `shift` and `s` and `down` keys are pressed. Try rearranging your `if` statements so that it checks for the more specific condition first. – John Gordon Sep 03 '20 at 17:34
  • 1
    Short answer: reverse the order of your conditions. The combination `"shift+s+right+down"` is a more specific "subset" of `"shift+s+down"`. – Brian61354270 Sep 03 '20 at 17:34

1 Answers1

1

The thing with elif is that the condition is tested only if the previous conditions were False. So when you press shift + s + down + right, if kb.is_pressed('shift+s+down') is triggered because you have pressed shift and s and down, and the elif is ignored.

If you reverse the order so that you check for the more specific condition first, it should work just fine.

def key_selected():
    if kb.is_pressed('shift+s+right+down'):
        return 'True2' 
    
    elif kb.is_pressed('shift+s+down'):
        return 'True1'
    
    else:
        return 'NOTHING'

does what you expect.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • So, it should also work if all elifs are replaced by ifs, right? – Saat Sep 03 '20 at 17:50
  • @Saat Yes, but then it will check for all conditions all the time, so the pressing `shift + s + down + right` would trigger that `if` _and_ the `shift + s + down` `if` – Pranav Hosangadi Sep 03 '20 at 17:51