我不是很擅长编程,但我目前正在为我弟弟做乘法学习程序,如果有任何方法可以做到,所以他必须在一定时间后回答,否则他的问题失败了.这是我的代码:
import random
F = 1
while F==1:
x = random.randint(1,10)
y = random.randint(1,10)
Result = y*x
print(y,"*",x)
Input = int(input())
if Result == Input:
print("correct")
else:
print("Wrong, correct result:",Result)
我希望这足够好。我将不胜感激任何帮助!非常感谢提前
答案 0 :(得分:1)
您可以使用 Python 的时间模块定义您自己的时间模块。 例如:
def timer(t):#t must be the time of the timer in seconds
while t:
mins,sec=divmod(t,60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end='\r')
time.sleep(1)
t=t-1
print("Time's Up")
答案 1 :(得分:1)
您可以使用 threading
模块创建一个线程并为该线程分配计时器,如果计时器用完则意味着子线程现在已死程序将响应您迟到。
解决办法如下:
import random
from threading import Thread
from time import sleep
def timer():
sleep(10) # wait for 10 seconds once the question is asked
return True
if __name__ == '__main__':
while True:
x = random.randint(1, 10)
y = random.randint(1, 10)
Result = y * x
print(y, "*", x)
time = Thread(target=timer) # Creating sub thread for timer processing
time.start() # starting the thread
Input = int(input())
if not time.isAlive(): # checking whether the timer is alive
print('You got late, Failed')
break
else:
pass
if Result == Input:
print("correct")
else:
print("Wrong, correct result:", Result)
如果您在主线程上使用 time.sleep()
方法,您的程序将挂起,您的系统暂时也是如此,因此我没有这样做,而是创建了一个新线程,该线程完全独立于您的主线程线程,你的系统就不会挂了。