我的函数'hello()'只是在屏幕上显示一个刺激2秒钟,在此期间可以按一个键。如果没有按下某个键,它将等待1秒,然后再次运行该功能,如果没有按键,则反复运行。当按下某个键时,它退出while循环并打印yes。由于某些原因,如果我让函数循环,例如,在我按下一个键之前循环4次,那么我将同时得到5个打印staments,而我只期望一个。有人能告诉我为什么它似乎在存储print语句,尽管我希望在我按下键之前永远无法访问print语句?在
def hello():
test = 1
running = 1
while running == 1:
for frame in range(short_frames): # 2 seconds
fix.draw()
window.flip()
allKeys = event.getKeys(keyList = ('g','h'))
for thisKey in allKeys:
if thisKey == 'g':
keyTime=core.getTime()
test = 2
elif thisKey == 'h':
keyTime=core.getTime()
test = 2
window.flip()
core.wait(1)
if test == 1: #if no key is pressed
hello() #run the function again
running = 2 #exit out of while loop
print "yes"
for i in range(1):
hello()
core.quit()
window.close()
hello()正在递归地调用自己。每次调用时它都会打印一次输出。为了获得你想要的效果,你需要这样的东西:
在while循环的底部,如果test没有改变(即没有按下一个键),running将被设置为1,循环将继续。如果按下2键,则循环将被设置为“运行”(2)。“yes”字符串只打印一次,因为hello()只调用一次。在
更新:
^{pr2}$您已经在
hello
中调用了函数hello
。这是递归。到第五次,你按一个键。它将打印您的thing
,并结束第5次调用hello
。您的程序返回到第4.thhello
,并捕获按下的键。函数hello
的第4次调用将再次打印,结束第4次hello
并返回到第3次调用hello
,以此类推。。。。。在你应该小心}。但这些代码会起作用的。在
recursion
。 我不知道,为什么需要变量test
和{相关问题 更多 >
编程相关推荐