Generate random number, save as variable, and use to call stimulus files


I have four stimulus files for a counterbalanced set of trials, and I need Psychopy to randomly select one file to use without cycling through all four, as would happen in a loop. My current strategy is inspired by the advice about counterbalancing in another Psychopy article. I have four conditions files, named file1, file2, etc. Following those instructions, I was able to do this by having a “group” field at the beginning of the experiment, then manually typing in a number 1-4 at the beginning of the experiment, and assigning a file using:


This worked well, but my supervisor wants Psychopy to generate the number randomly and internally, to save time on our end during data collection. I’ve inserted a code block before the trials in builder mode, where I’m trying to generate a random integer 1-4, save it as a variable (filepath), and then in the conditions field, call up the specific file using this text:


Can I accomplish this using a code chunk in the Builder mode? Thank you!

Just use filepath as your variable name if you’ve defined it in a code component

Right thanks, that’s what I’m asking about. If possible, how do you generate a random number in the code chunk that saves as a variable that I can then use?

filepath=str(randint(1,4)) should set filepath as ‘1’, ‘2’ or ‘3’.

This seems to be working. Thank you very much for your help, on both this question and my previous one.

For anyone else reading this, I set each file with the orders of conditions to a number 1-4, then for my conditions file, specified $filepath+".xlsx", which seems to work.