Keyboard sensor runs python controller's code always twice?

How could I make it so that my code is ran only once when I hit a key?

Example .blend attached
coderun.blend (457 KB)

you have to use:

if cont.sensors[“Keyboard”].positive:
# do something

In developing sevi’s explanation, sensors have two states, positive and negative. With things like keyboard sensors, they are positive when pressed and negative when unpressed (released). When the state changes the controller is triggered. If you modify the pulse modes then they will also trigger the connected controller whenever the sensor state is the same as that pulse mode; triggering constantly whilst positive if the True level triggering is enabled, and vice versa for negative.

Checking for positive will only execute code on the positive triggering of the controller by that sensor. If you use module mode then you do not have to indent all your code after the check, instead doing something along these lines:



def keyboard_test(cont):
    keyboard = cont.sensors['Keyboard']

    if not keyboard.positive:
        return

    # Do normal stuff here