Q:

python pygame how to debounce a button?

so im building a pi based robot.
It uses a ps3 controller for input. When the X button is pressed, it takes a photo. For some reason, it takes around 5 shots at a time. Is there a way to bounce the input so it only recognises one press?
I'm assuming it's registering multiple presses each time... Part of the code is attached, but I must state most of it is used from piborg.org
joystick = pygame.joystick.Joystick(0)

button_take_picture = 14            # X button

while running:
    # Get the latest events from the system
    hadEvent = False
    events = pygame.event.get()
    # Handle each event individually
    for event in events:
        if event.type == pygame.QUIT:
            # User exit
            running = False
        elif event.type == pygame.JOYBUTTONDOWN:
            # A button on the joystick just got pushed down
            hadEvent = True
        elif event.type == pygame.JOYAXISMOTION:
            # A joystick has been moved
            hadEvent = True
        if hadEvent:
            if joystick.get_button(button_take_picture):
                take_picture()

A:

What seems to be happening is that the X button stays down for multiple frames. Some other events might happen during this time, causing a call to take_picture() in your code for every frame. To fix this, you can either call take_picture() only on JOYBUTTONUP (when the button is released), or move the if joystick.get_button(button_take_picture) part to inside the pygame.JOYBUTTONDOWN section. 
Alternatively, you could use another variable to indicate whether the picture was already taken, like this:
picture_was_taken = False

while running:
     hadEvent = False
     events = pygame.event.get()
     for event in events:
       ...
       if event.type == pygame.JOYBUTTONUP:
           if not joystick.get_button(button_take_picture)
               picture_was_taken = False
       ...
       if hadEvent:
           if joystick.get_button(button_take_picture) and not picture_was_taken:
               take_picture()
               picture_was_taken = True

