-3

With the below program, whenever I press the "a" key, the keypresses variable increments by 1. The problem is, if I don't immediately let go fo the key, the keypresses variable continues to increment by 1.

How can I get it to increment (and print) whenever I press the key, ignoring the hold aspect?

import keyboard
keypresses = 0
while True:
    if keyboard.is_pressed("a"):
        keypresses = keypresses +1
        print(keypresses)   
        print("A Key Pressed")
        break
Red
  • 26,798
  • 7
  • 36
  • 58
  • Did you mean to break out of the loop when `a` is pressed? – jarmod Apr 16 '22 at 16:38
  • not really, i did so i dont get constantly print values non stop – Princess_Kylie Apr 16 '22 at 16:39
  • 1
    Your comment "so i dont get constantly print values non stop" seems to conflict with your question "How can i get it to increment and print whenever i press the key, not just once?" What is your desired outcome? – jarmod Apr 16 '22 at 16:44
  • My desire outcome is to print whenever i press the key, and count increments. – Princess_Kylie Apr 16 '22 at 16:47
  • 1
    What is "the key"? Are you trying to print every single key that is pressed but only count the number of times that `a` is pressed? – jarmod Apr 16 '22 at 16:53

3 Answers3

3

I understand that you want it so that pressing and holding only prints once (not indefinitely), and it will print again as long as the a key is released and pressed again.

Define a variable, pressing, to get if the key is still being pressed, or released:

import keyboard

keypresses = 0
pressing = False

while True:
    if keyboard.is_pressed("a"):
        if not pressing:
            pressing = True
            keypresses = keypresses +1
            print(keypresses)   
            print("A Key Pressed")
    else:
        pressing = False
Red
  • 26,798
  • 7
  • 36
  • 58
1

I'd remove the break statement. On the Python docs you can see that break exits the innermost for/while loop, in your case the that loop would be the

while True:
Liam
  • 461
  • 4
  • 27
Marco Balo
  • 336
  • 2
  • 9
1

if you remove the break statement like this:

import keyboard
keypresses = 0
while True:
    if keyboard.is_pressed("a"):
        keypresses = keypresses +1
        print(keypresses)   
        print("A Key Pressed")
    break

this does not work, and when you run it, it is instantly finished the while cycle. because the keyboard.is_pressed only detect now and precisely because of this, which caused too many cpu

if you are in windows , you can use msvcrt to instead :-)

zephms
  • 11
  • 3