Same as with the mouse, when a key is pressed an event is generated: pygame.KEYDOWN. To know which specific key it is, we compare it with the possible options. For example:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
exit(0)
elif event.key == pygame.K_LEFT:
print("You pressed LEFT")
elif event.key == pygame.K_RIGHT:
print("You pressed RIGHT")
This is what the program does:
Each KEYDOWN event comes with a key, telling which key it was that the player pressed.
Inside pygame there are a bunch of things that represent each key, and we can use to compare. For example, pygame.K_q represents the 'Q' key in the keyboard. To know if the player pressed this key, we compare it with event.key, like this: event.key == pygame.K_q. If instead we want to know when the left arrow key was pressed, with compare with pygame.K_LEFT.
Let's see how well you understood all that: