| Reference | Downloads | Github

Variables defined in 'Begin routine' don't seem to be created

OS Win10

PsychoPy version 2020 1.3

What are you trying to achieve?:
Define a variable at the start of the trial, which is referred to in a polygon component’s position field.

What did you try to make it work?:
I have added a code component to my ‘trial’ routine. Under the ‘begin routine’ I have added:

targetPos=(0.0, 0.0)

In my routine, I have added a Polygon component, and in the position field I have added:


Next to this field, I have clicked on the drop-down menu and selected ‘set every repeat’

What specifically went wrong when you tried that?:
When I run this, the polygon doesn’t appear, and I receive the message:

ori=0, pos=targetPos,
NameError: name ‘targetPos’ is not defined

However, when I define targetPos under the ‘BeginExperiment’ tab in the code component, it works.

As you can see, I am very new to using the builder! Thank you for your help with this very newby question.

Is your builder “code component” at the top of your routine? Your routine runs in the order you place them in the builder menu. Basically, you may be trying to place your stimulus before it is defined in the code component. I know this mistake all too well…

To quote the “Code Components” page directly… " Be aware that the code for each of the components in your [Routine] are executed in the order they appear on the [Routine] display (from top to bottom). If you want your Code Component to alter a variable to be used by another component immediately, then it needs to be above that component in the view. You may want the code not to take effect until next frame however, in which case put it at the bottom of the [Routine]. You can move Components up and down the [Routine] by right-clicking on their icons." from:

Hope that helps!

Yep, that was it. Thank you!