0

I am learning python using Jupytor Notebook and I want to write a typing tutor program in Python for my first program. I need python to detect a key being pressed and then print it on the screen. I got some code from stackoverflow and I modified it. The code works when there is only one letter to press. The problem is it prints the letter twice - why? I want it to print it once. Then when you add more code for more letters you have to press the letter twice for it to appear on the screen once. This is the code for one letter key press detect.

import keyboard

while True:

    if keyboard.read_key() == chr(97):

        print (chr(97))

output is

a
a

I thought the output would be just one "a" because there is only one print statement.

THIS IS THE CODE WHEN YOU HAVE TO PRESS THE KEY TWICE BEFORE THE LETTER APPEARS ON THE SCREEN. THAT IS THE FIRST TIME YOU PRESS A LETTER NOTHING HAPPENS THEN YOU PRESS THAT LETTER AGAIN AND THAT'S WHEN IT APPEARS ON THE SCREEN. YOU CAN SEE THE CODE IS THE SAME, IT JUST HAS MORE LETTERS TO DETECT. I WANT TO PRINT OUT ALL 26 LETTERS BY ONLY PRESSING EACH LETTER ONCE AND IT PRINTS TO THE SCREEN ONCE.

import keyboard

while True:

    if keyboard.read_key() == chr(97):

        print("You pressed a")

    if keyboard.read_key() == chr(98):

        print("You pressed b")

    if keyboard.read_key() == chr(99):

        print("You pressed c")

    if keyboard.read_key() == chr(100):

        print("You pressed d")

This is some output

You pressed a

You pressed b

You pressed c

You pressed c

You pressed c

You pressed d

You pressed d

You pressed d
Chris
  • 1
  • 1
  • 1
    Does this answer your question? [detect key press in python?](https://stackoverflow.com/questions/24072790/detect-key-press-in-python) – buran Sep 19 '20 at 11:49
  • No buran. That is where I got the way to detect a keypress using method 1. – Chris Sep 19 '20 at 12:18
  • It checks that you pressed that key, prints the sentence, and continues to the next loop and vice versa. You need to use `keyboard.record()` or `keyboard.wait(key)` – Nouman Oct 11 '20 at 16:40

0 Answers0