Skip to content
← Back to Community
how to detect keys
Profile icon
mattman101

I'm making a project where it gives you a letter and you have to press it in order to get a point. does anyone know how to detect which key is being pressed? by the way I am new to coding and not that good with python.

Answered by Bookie0 [earned 5 cycles]
View Answer
Voters
Profile icon
CordanPollock
Profile icon
figglediggle
Profile icon
mattman101
Comments
hotnewtop
Profile icon
Bookie0

You could do like a while true loop, then a list with all the different chars, then use random to output one of the letters, input the user for them to type a letter, and using conditionals, determine if what the user typed is that char. And a variable for the points that increments when you get it correct.

Like:

import random # imports random points = 0 # initial number of points chars = ['a', 'b', 'c'] # list containing some chars (you can modify it) while True: # while true loop random_char = random.choice(chars) # randomly selects an item out of chars print("Press " + str(random_char) + "!") # tells user what to press user_press = input("> ") # input for user to type that char # conditionals if user_press == random_char: # if user pressed that random char print("Correct!") points += 1 # adds 1 to points else: # if user didn't print("No!")

That's not really exactly what key out of the keyboard is pressed, but close enough. you can also use getch() so you don't have to press enter (unlike input()). For getch(), check this out.

And check out this for detecting a key press in python by installing keyboard.

Profile icon
mattman101

thank you I never knew about getch(). I am still not sure how to use it. I swapped it out for the input in that line of code you gave me and it gave me an error

Profile icon
Bookie0

@mattman101 np!

for getch, use it like so:

import getch print("Type a char") char = getch.getch() # user can now type 1 char without pressing enter # getch also returns a string print("You typed " + char)

This should work :)

Profile icon
mesquite2234
from getch import * thing = getch() if thing == other_thing; #stuff
Profile icon
InvisibleOne

Personally, I use getch

Profile icon
KingsleyDockeri
Profile icon
RYANTADIPARTHI

Solution

Use the keyboard module. HEre's a link to help.

https://www.geeksforgeeks.org/keyboard-module-in-python/

IT should help