【问题标题】:Is there a way to add a timer to a python programm?有没有办法在 python 程序中添加计时器?
【发布时间】:2021-03-16 09:02:56
【问题描述】:

我对编程不是很好,但我目前正在为我的兄弟做一个乘法学习程序,并且正在徘徊是否有任何方法可以做到这一点,所以他必须在一定的时间后回答,否则他会失败.这是我的代码:

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)

我希望这已经足够好了。我将不胜感激任何帮助!非常感谢提前

【问题讨论】:

    标签: python-3.x time


    【解决方案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() 方法,您的程序将挂起,您的系统暂时也会挂起,所以我没有这样做,而是创建了一个完全独立于您的主线程工作的新线程,并且您的系统不会挂起。

    【讨论】:

    • 你也可以通过改变 sleep() 方法的参数值来增加时间限制
    【解决方案2】:

    您可以使用 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 2023-03-23
      • 2021-04-28
      • 1970-01-01
      相关资源
      最近更新 更多