-3

I've been working on a python script to detect keypresses. It uses the pygame module. My issue is when pressing the up, down and right arrow keys but not the left. I have seen this however it does not help me with my problem. The issue is when I press Up, Down or Right it prints the appropriate text and them executes the else statement as well replacing even.unicode with this weird symbol whoever when I press the left arrow key it prints "The key is Left" and no more, like it's supposed to. Also pressing any normal key on the keyboard works fine. Weird HUH. If you can spot the boo boo I've made that would be really great. My code is below, you can copy and paste this into idle for 2.7 if you have pygame installed and see what I mean.

#Python key detector, requires pygame module, uses python 2.7
#Import libraries
import pygame
import sys
from pygame.locals import *
#Init display
pygame.display.init()
#Infinite loop
while (True):
    #Event detector
    for event in pygame.event.get():
        #If a key is pressed
        if event.type == KEYDOWN:
            if event.key == 99:
                sys.exit()
            if event.key == 273:
                print "The key is Up"
            if event.key == 275:
                print "The key is Right"
            if event.key == 274:
                print "The key is Down"
            if event.key == 276:
                print "The key is Left"
            else:
                print "The key is " + event.unicode
Community
  • 1
  • 1
Curious Programmer
  • 433
  • 1
  • 5
  • 14
  • I recommend looking into [dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries), it saves you having long `if` chains. They're easy to use to print back a string, a little more complicated when you're actually going to use them to run code but it is possible using functions. – SuperBiasedMan Aug 24 '15 at 10:10
  • @SuperBiasedMan Well thanks for the suggestion, I must look into them. Sounds like they could save me a bit of time. – Curious Programmer Aug 24 '15 at 10:12

1 Answers1

6

you need to use elif; otherwise this is just a new check and the else statement is executed if the last if clause fails.

#Event detector
for event in pygame.event.get():
    #If a key is pressed
    if event.type == KEYDOWN:
        if event.key == 99:
            sys.exit()
        elif event.key == 273:
            print "The key is Up"
        elif event.key == 275:
            ...
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111