Error "name" defined

hello, I am very new to Psychopy and trying and programming an IAT, where participants have to categorize stimuli (left vs right). I have problem about giving feedback . Here is my part of coding …

# ------Prepare to start Routine "trial"-------
# update component parameters for each repeat
if key_resp_2.corr == 1:
    requiredallowed = "e"
    requiredCorrect = "e"
    feedbackAllowed = "i"
    feedbackCorrect = "i"
text_2.setText(word)
key_resp_2.keys = []
key_resp_2.rt = []
key_resp_3.keys = []
key_resp_3.rt = []
# keep track of which components have finished
trialComponents = [text_2, key_resp_2, key_resp_3, text_4]
for thisComponent in trialComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
trialClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1
continueRoutine = True

# -------Run Routine "trial"-------
while continueRoutine:
    # get current time
    t = trialClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=trialClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    if key_resp_2.corr == 1:
        msg=""
    else:
        msg="X"
    
    
    # *text_2* updates
    if text_2.status == NOT_STARTED and tThisFlip >= 0.3-frameTolerance:
        # keep track of start time/frame for later
        text_2.frameNStart = frameN  # exact frame index
        text_2.tStart = t  # local t and not account for scr refresh
        text_2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(text_2, 'tStartRefresh')  # time at next scr refresh
        text_2.setAutoDraw(True)
    
    # *key_resp_2* updates
    waitOnFlip = False
    if key_resp_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        key_resp_2.frameNStart = frameN  # exact frame index
        key_resp_2.tStart = t  # local t and not account for scr refresh
        key_resp_2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(key_resp_2, 'tStartRefresh')  # time at next scr refresh
        key_resp_2.status = STARTED
        # AllowedKeys looks like a variable named `requiredAllowed`
        if not type(requiredAllowed) in [list, tuple, np.ndarray]:
            if not isinstance(requiredAllowed, str):
                logging.error('AllowedKeys variable `requiredAllowed` is not string- or list-like.')
                core.quit()
            elif not ',' in requiredAllowed:
                requiredAllowed = (requiredAllowed,)
            else:
                requiredAllowed = eval(requiredAllowed)
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(key_resp_2.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(key_resp_2.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if key_resp_2.status == STARTED and not waitOnFlip:
        theseKeys = key_resp_2.getKeys(keyList=list(requiredAllowed), waitRelease=False)
        if len(theseKeys):
            theseKeys = theseKeys[0]  # at least one key was pressed

but error message is showing :

if not type(requiredAllowed) in [list, tuple, np.ndarray]:

NameError: name ‘requiredAllowed’ is not defined

I think ‘requiredAllowed’ was already defined… what I missed??

Hi @apple, the error may occur because you create the requiredAllowed variable conditionally, based on a correct response. If this is causing the error, then perhaps you can have a generic response assigned to the variable. So, in the “Begin Experiment” tab, set the variable as something like:

requiredAllowed = 'space'

Thank you for the reply…

No problem. Did this help solve the error?

Actually, despite your help, the error remains.
Perhaps I wasn’t used to psychopy, so I didn’t get it right.
But thank you very much for your reply.

Well we can still try and solve it. It would be best if you shared your task, so I can take a look at that particular error.

First of all, thank you very much for your reply once more.
As I mentioned, I want to make programming an IAT where participants have to categorize stimuli (left vs right). It has 7blocks and each block has 20 or 40 trials. When participant do wrong performance, the feedback show inside trials. Because I’m not used to it yet, I first make giving feedback.

I want to make to make it below:
The correct response key is “i” in this trial. if participant do wrong performance(press the “e” key), the feedback (“X”) show up.

I tried it again, but the same error still appears.

if not type(requireall) in [list, tuple, np.ndarray]:

NameError: name ‘requireall’ is not defined

here is my part of coding …

# Initialize components for Routine "instruction"
instructionClock = core.Clock()
instruc = visual.TextStim(win=win, name='instruc',
    text='hello',
    font='Arial',
    pos=(0, 0), height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);
res = keyboard.Keyboard()

# Initialize components for Routine "trial"
trialClock = core.Clock()
msg=""
target = visual.TextStim(win=win, name='target',
    text='default text',
    font='Arial',
    pos=(0, 0), height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);
require = keyboard.Keyboard()
feedback = keyboard.Keyboard()
feed = visual.TextStim(win=win, name='feed',
    text='default text',
    font='Arial',
    pos=(0, 0), height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-4.0);

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine 

# ------Prepare to start Routine "instruction"-------
# update component parameters for each repeat
res.keys = []
res.rt = []
# keep track of which components have finished
instructionComponents = [instruc, res]
for thisComponent in instructionComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
instructionClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1
continueRoutine = True

# -------Run Routine "instruction"-------
while continueRoutine:
    # get current time
    t = instructionClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=instructionClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *instruc* updates
    if instruc.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        instruc.frameNStart = frameN  # exact frame index
        instruc.tStart = t  # local t and not account for scr refresh
        instruc.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(instruc, 'tStartRefresh')  # time at next scr refresh
        instruc.setAutoDraw(True)
    
    # *res* updates
    waitOnFlip = False
    if res.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        res.frameNStart = frameN  # exact frame index
        res.tStart = t  # local t and not account for scr refresh
        res.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(res, 'tStartRefresh')  # time at next scr refresh
        res.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(res.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(res.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if res.status == STARTED and not waitOnFlip:
        theseKeys = res.getKeys(keyList=['e', 'i'], waitRelease=False)
        if len(theseKeys):
            theseKeys = theseKeys[0]  # at least one key was pressed
            
            # check for quit:
            if "escape" == theseKeys:
                endExpNow = True
            res.keys = theseKeys.name  # just the last key pressed
            res.rt = theseKeys.rt
            # a response ends the routine
            continueRoutine = False
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in instructionComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "instruction"-------
for thisComponent in instructionComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('instruc.started', instruc.tStartRefresh)
thisExp.addData('instruc.stopped', instruc.tStopRefresh)
# check responses
if res.keys in ['', [], None]:  # No response was made
    res.keys = None
thisExp.addData('res.keys',res.keys)
if res.keys != None:  # we had a response
    thisExp.addData('res.rt', res.rt)
thisExp.addData('res.started', res.tStartRefresh)
thisExp.addData('res.stopped', res.tStopRefresh)
thisExp.nextEntry()
# the Routine "instruction" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=2, method='random', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('1206\\통합 문서1.xlsx'),
    seed=None, name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial:
        exec('{} = thisTrial[paramName]'.format(paramName))

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial:
            exec('{} = thisTrial[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "trial"-------
    # update component parameters for each repeat
    if require.corr==1:
        requireall = "i"
        requirecor = "i"
        feedbackall = "e"
        feedbackcor = "e"
    target.setText(word)
    require.keys = []
    require.rt = []
    feedback.keys = []
    feedback.rt = []
    feed.setText(msg)
    # keep track of which components have finished
    trialComponents = [target, require, feedback, feed]
    for thisComponent in trialComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    trialClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    continueRoutine = True
    
    # -------Run Routine "trial"-------
    while continueRoutine:
        # get current time
        t = trialClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=trialClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if require.corr==1:
            msg=""
        else:
            msg="X"
        
        # *target* updates
        if target.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            target.frameNStart = frameN  # exact frame index
            target.tStart = t  # local t and not account for scr refresh
            target.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(target, 'tStartRefresh')  # time at next scr refresh
            target.setAutoDraw(True)
        
        # *require* updates
        waitOnFlip = False
        if require.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            require.frameNStart = frameN  # exact frame index
            require.tStart = t  # local t and not account for scr refresh
            require.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(require, 'tStartRefresh')  # time at next scr refresh
            require.status = STARTED
            # AllowedKeys looks like a variable named `requireall`
            if not type(requireall) in [list, tuple, np.ndarray]:
                if not isinstance(requireall, str):
                    logging.error('AllowedKeys variable `requireall` is not string- or list-like.')
                    core.quit()
                elif not ',' in requireall:
                    requireall = (requireall,)
                else:
                    requireall = eval(requireall)
            # keyboard checking is just starting
            waitOnFlip = True
            win.callOnFlip(require.clock.reset)  # t=0 on next screen flip
            win.callOnFlip(require.clearEvents, eventType='keyboard')  # clear events on next screen flip
        if require.status == STARTED and not waitOnFlip:
            theseKeys = require.getKeys(keyList=list(requireall), waitRelease=False)
            if len(theseKeys):
                theseKeys = theseKeys[0]  # at least one key was pressed
                
                # check for quit:
                if "escape" == theseKeys:
                    endExpNow = True
                if require.keys == []:  # then this was the first keypress
                    require.keys = theseKeys.name  # just the first key pressed
                    require.rt = theseKeys.rt
                    # was this 'correct'?
                    if (require.keys == str(requirecor)) or (require.keys == requirecor):
                        require.corr = 1
                    else:
                        require.corr = 0
                    # a response ends the routine
                    continueRoutine = False
        
        # *feedback* updates
        waitOnFlip = False
        if feedback.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            feedback.frameNStart = frameN  # exact frame index
            feedback.tStart = t  # local t and not account for scr refresh
            feedback.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(feedback, 'tStartRefresh')  # time at next scr refresh
            feedback.status = STARTED
            # AllowedKeys looks like a variable named `feedbackall`
            if not type(feedbackall) in [list, tuple, np.ndarray]:
                if not isinstance(feedbackall, str):
                    logging.error('AllowedKeys variable `feedbackall` is not string- or list-like.')
                    core.quit()
                elif not ',' in feedbackall:
                    feedbackall = (feedbackall,)
                else:
                    feedbackall = eval(feedbackall)
            # keyboard checking is just starting
            waitOnFlip = True
            win.callOnFlip(feedback.clock.reset)  # t=0 on next screen flip
            win.callOnFlip(feedback.clearEvents, eventType='keyboard')  # clear events on next screen flip
        if feedback.status == STARTED and not waitOnFlip:
            theseKeys = feedback.getKeys(keyList=list(feedbackall), waitRelease=False)
            if len(theseKeys):
                theseKeys = theseKeys[0]  # at least one key was pressed
                
                # check for quit:
                if "escape" == theseKeys:
                    endExpNow = True
                feedback.keys = theseKeys.name  # just the last key pressed
                feedback.rt = theseKeys.rt
                # was this 'correct'?
                if (feedback.keys == str(feedbackcor)) or (feedback.keys == feedbackcor):
                    feedback.corr = 1
                else:
                    feedback.corr = 0
        
        # *feed* updates
        if feed.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            feed.frameNStart = frameN  # exact frame index
            feed.tStart = t  # local t and not account for scr refresh
            feed.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(feed, 'tStartRefresh')  # time at next scr refresh
            feed.setAutoDraw(True)
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in trialComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "trial"-------
    for thisComponent in trialComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    trials.addData('target.started', target.tStartRefresh)
    trials.addData('target.stopped', target.tStopRefresh)
    # check responses
    if require.keys in ['', [], None]:  # No response was made
        require.keys = None
        # was no response the correct answer?!
        if str(requirecor).lower() == 'none':
           require.corr = 1;  # correct non-response
        else:
           require.corr = 0;  # failed to respond (incorrectly)
    # store data for trials (TrialHandler)
    trials.addData('require.keys',require.keys)
    trials.addData('require.corr', require.corr)
    if require.keys != None:  # we had a response
        trials.addData('require.rt', require.rt)
    trials.addData('require.started', require.tStartRefresh)
    trials.addData('require.stopped', require.tStopRefresh)
    # check responses
    if feedback.keys in ['', [], None]:  # No response was made
        feedback.keys = None
        # was no response the correct answer?!
        if str(feedbackcor).lower() == 'none':
           feedback.corr = 1;  # correct non-response
        else:
           feedback.corr = 0;  # failed to respond (incorrectly)
    # store data for trials (TrialHandler)
    trials.addData('feedback.keys',feedback.keys)
    trials.addData('feedback.corr', feedback.corr)
    if feedback.keys != None:  # we had a response
        trials.addData('feedback.rt', feedback.rt)
    trials.addData('feedback.started', feedback.tStartRefresh)
    trials.addData('feedback.stopped', feedback.tStopRefresh)
    trials.addData('feed.started', feed.tStartRefresh)
    trials.addData('feed.stopped', feed.tStopRefresh)
    # the Routine "trial" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    thisExp.nextEntry()
    
# completed 2 repeats of 'trials'


# Flip one final time so any remaining win.callOnFlip() 
# and win.timeOnFlip() tasks get executed before quitting
win.flip()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()

This is the same issue, with a different variable name. The actual issue originates from using a variable to define your allowed keys in your keyboard component, but the variable is being used before it has been defined, or given a value. To fix you need to add the following to the “Begin Experiment” tab in your code component:

requireall = 'space'  # Or whatever you want the default value to be

Thank you for your help.
I tried again and now no error appears.
Thank you…

Hi, David.

I am sure this topic is quite similar to my issue. However, I already posted it here.

do you mind to give me some help with the issue please?