Search code examples
pythonpsychopy

Python/Psychopy: passing information between functions


I am having some trouble passing information between two functions. Within my 'trial' function (see code below) I am checking for keypresses and expecting to exit out of the while loop if a 'g or 'h' key is pressed. The while loop is dependent on test=1. From within my 'check_keys' function, as soon as the 'g' or 'h' key is pressed, test switches to 2; I would then expect to exit the while loop. As it stands, as I'm pressing keys, I can see they are being registered (due to the print statements), but it is not exiting the while loop. There seems to be an issue getting my main while loop to see that 'test' has switched to 2 from within my 'check_keys' function. I have tried changing 'test' to a global variable, but I'm still stuck with the same issue. Clearly information isn't being passed between both functions.

window = visual.Window([600,600],fullscr=False,color=("black"), allowGUI=True, monitor='testMonitor', units='deg')

global test
def check_keys():       
    allKeys = event.getKeys(keyList = ('g','h','escape'))
    for thisKey in allKeys:
        if thisKey == 'g':
            print "g"
            test = 2

        elif thisKey == 'h':
            print "h"
            test = 2

def trial():
    global test
    test = 1

    while test ==1:
        check_keys()

for i in range(1):
    trial()

In short; why am I stuck in the while loop despite that my conditional 'test' variable has changed?

Cheers, Steve


Solution

  • You're stuck because you haven't declared test as a global inside of your check_keys() method. That being said, what you should do is have check_keys return the value of test, and then just keep track of it in main:

    def trial():
        test = 1
    
        while test == 1:
            test = check_keys()