<p>您将要使用<a href="https://docs.python.org/2/library/threading.html" rel="nofollow">threading</a>,并打开一个并行线程来计算该时间(可能通过使用时间。睡觉())和return一旦完成,一旦返回,主线程将停止执行并返回结果。<br/>
在主程序中使用sleep()只会暂停执行一段时间,据我所知,这不是您想要的。您希望用户能够在计时器运行时与程序交互。这就是使用线程模块中的线程所允许的。在</p>
<p>下面是一个使用线程的快速示例(如果需要任何特定的东西,请调整它):</p>
<pre class="lang-python prettyprint-override"><code>import random
import time
def main():
thread_stop = threading.Event()
thread = threading.Thread(target=user_thread, args=(2, thread_stop))
time.sleep(20)
thread_stop.set()
def user_thread(arg1, stop_event):
t = 0
while(not stop_event.is_set()):
a = random.randint(2, 10)
b = random.randint(2, 10)
print("How much is", a, "times", b)
odg = int(input("Answer ?"))
if odg == a * b:
print("Correct")
t += 1
else:
print("Incorrect")
print("Your points are", t)
main()
</code></pre>
<p><br/>
这里还有一个例子,如果20秒时间到了,信号会在回答过程中停止用户并对结果进行计数。这个例子使用signals,它本身就是一个有趣的模块来控制执行流,如果有机会,您应该检查它的文档。<br/>我还意识到您的代码中还有一个错误,我忽略了这一点,现在在两个示例中都已更正了,当您要增加“t”时,请使用“t+=1”,因为“t=+1”是不正确的,所以最后一个表达式每次都只是给t赋值“正”一个,所以不会增加。干杯!在</p>
^{pr2}$
<p>另外,别忘了添加到健全性检查中,这样无效的用户输入不会破坏代码。我把这个留给你;)</p>