Search code examples
pythonpython-3.xkeyboardkeypynput

Elif condition that is intended to break the function when it reaches a certain value doesn't work


i have been working on a program that detects the number of times "enter" has been pressed, the problem is that the elif/if condition that is supposed to break the function when the variable reaches a certain value, keeps counting the number of times "enter" has been pressed instead of breaking the function.

from pynput import keyboard

keystroke = 0

def on_release(key):
    print(key)
    global keystroke
    if key == keyboard.Key.enter:
        keystroke += 1 #this sums to the variable keystroke +1.
        print(keystroke)
    elif keystroke > 3: #This intends to break the fuction when keystroke reaches or surpasses 3.
        return False

with keyboard.Listener( #Calling the function here.
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()


......

this is the output.

Output 

key.enter
1
key.enter
2
key.enter
3
key.enter
4
....

Solution

  • Because of the elif statement, your current program checks the number of keystrokes only if a key other than Enter has been pressed. Instead, you should replace the elif with a separate if statement so the condition is checked even when you press Enter.

    Also, if you want the function to break when keystroke reaches 3, replace ">" with ">=":

    from pynput import keyboard
    
    keystroke = 0
    
    def on_release(key):
        print(key)
        global keystroke
        if key == keyboard.Key.enter:
            keystroke += 1 #this sums to the variable keystroke +1.
            print(keystroke)
        if keystroke >= 3: #This intends to break the fuction when keystroke reaches or surpasses 3.
            return False
    
    with keyboard.Listener( #Calling the function here.
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()