在Python中循环的多次迭代中执行一次操作

2024-09-23 16:21:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写的代码在屏幕上显示一个形状,并允许通过向上/向下箭头键操作该形状。我一直试图让它做的是使形状变化的数量取决于按键的顺序;只要输入与初始按键相同,形状变化的量就会很大。但是,当第一次按键“反转”发生时(例如,为了进行微调),在该点之后的每一次按键(无论是否与初始按键相同)都应该以较小的比例改变圆圈(不是交互的,只是0.1厘米的变化而不是2厘米)。密码是用神经病写的。在

我想我还没有掌握循环的设置方式,但是我不知道如何改变循环以实现我想要的。为实际的代码道歉,而不是一个最小的例子-任何建议都是非常感谢。在

for thisTrial in trials:
    endKey = 0
    nKeypress = 0
    count = 0
    counting = 0
    if thisTrial == 'ellipse':
        ellipseHeightinit = 7.6,1.9 + (round(numpy.random.uniform(-1,1),1))
    elif thisTrial == 'circle':
        ellipseHeightinit = 7.6,7.6 + (round(numpy.random.uniform(-1,1),1))
    ellipseHeight = ellipseHeightinit
    ellipseStim.setSize(ellipseHeight, log = False) # set the initial size of the shape  
    while endKey == 0:
        ellipseStim.setAutoDraw(True)
        win.flip() # flip the window to see the stimuli
        allKeys = event.waitKeys() 
        if count < 1: #store the first keypress made
            for thisKey in allKeys:
                firstKeypress = thisKey
                count += 1
                event.clearEvents()
        for thisKey in allKeys: # change the size of the shape depending on key pressed
            if thisKey == 'up':
                nKeypress = nKeypress + 1
            elif thisKey == 'down':
                nKeypress = nKeypress - 1
            elif thisKey == 'space':
                endKey = 1
            while counting < 1: # attempt to make step size large until reversal
                if thisKey == firstKeypress:
                    ellipseHeight = 7.6, ellipseHeightinit[1] + nKeypress*20
                    break
                elif thisKey != firstKeypress:
                    ellipseHeight = 7.6, ellipseHeightinit[1] + nKeypress*0.1
                    counting += 1
                    break
       ellipseStim.setSize(ellipseHeight, log = False) # set new shape size     
    ellipseStim.setAutoDraw(False)

Tags: theinforsizeif按键形状elif