Search code examples
pythonloopsenumeration

Pause for loop and wait for user key press every 'n' iterations. - Python


I have for loop which looks like this:

for trial in trials:
    stim.text = trial[0]
    stim.color = trial[1]
    win.flip()
    isi = random.random() * 2.0
    core.wait(isi)
    stim.draw()
    event.clearEvents()
    displaytime = win.flip()
    keys = event.waitKeys(keyList=answer_keys.keys(), timeStamped=True)
    rt =  keys[0][1] - displaytime
    trialNum +=1
    if trial[0] == trial[1]:
        condition = 'congruent'
    elif trial[0] != trial[1]:
        condition = 'incongruent'
    logfile.write('{},{},{},{},{},{:.3f}\n'.format(trialNum, trial[0], trial[1], condition, keys[0], rt))

what I want to do is pause the for loop at a given number of iterations and wait for the users key press to continue.

So if I supplied the value 5 this would pause the loop every 5 iterations.

Anymore questions or info required let me know. All help is greatly appreciated.


Solution

  • you can use input built-n function at your desired number of iterations:

    input("Press Enter to continue...")
    

    let's say that you want at n iterations to make the pause:

    n = 7
    
    for i in range(1, 20):
        if i % n == 0:
            input("Press Enter to continue...")
    

    if you iterate over a list with different kind of elements:

    for i, e in enumerate(my_list):
        if i % n == 0:
            input("Press Enter to continue...")
        ... other code...