Ask coding questions

← Back to all posts
How do I detect Keystrokes
CarterTimmons03

I am trying to break out of a loop once the SPACE key is pressed. I was using GetKey but it doesn't let the loop continue until it is executed.

from getkey import getkey, keys

while True:
key = getkey() #code does not continue until a key is pressed
if key == keys.SPACE:
break
print("No SPACE")

Voters
CarterTimmons03
Comments
hotnewtop
SixBeeps

That's because you're calling break. break will always escape the loop. Instead, I think you're looking for continue.

CarterTimmons03

@SixBeeps so if I replace break with continue, as soon as Space is pressed, the loop will stop?

CarterTimmons03

@CarterTimmons03 I want the loop to go forever until space is pressed

SixBeeps

@CarterTimmons03 Oh, my apologies. Could you revert your code back to how it was?

CarterTimmons03

@SixBeeps
i reverted it. I just want to end the loop once space is pressed
(thanks for trying to help me :D)

SixBeeps

@CarterTimmons03 Hmm, this code seems to work as you described. When I hit space, it leaves the loop. Any other character makes it continue.

CarterTimmons03

@SixBeeps Well, I want it to continuously print("No Space") until space is pressed (Not just when a different key is pressed). It would look like:
No Space
No Space
No Space
No Space
No Space
No Space
Space