Search code examples
pythontimepython-multithreading

How to give the user certain amount of time to answer and print a message as soon as the time expires? (Python)


I have tried to use multi-threading for limiting the input time for the user, but this code doesn't seem to work.

# giving the user less than 5 seconds to enter a number

import time
from threading import Thread


def ask():
    start_time = time.time()
    a = float(input("Enter a number:\n"))
    time.sleep(0.001)


def timing():
    if time.time() - start_time > 5: 
        print("Time's Up")
        quit()
    time.sleep(0.001)


t1 = Thread(target=ask)
t2 = Thread(target=timing)
t1.start()
t2.start()
t1.join()
t2.join()

Solution

  • You need to put timing function in infinite mode. Bcz it's running only one time.

    Try below code:

    import time
    import os
    from threading import Thread
    
    start_time = time.time()
    a = None
    
    def ask():
        global start_time
        start_time = time.time()
        global a
        a = float(input("Enter a number:\n"))
        time.sleep(0.001)
    
    
    def timing():
        while True:
            global a
            if a is not None:
                break
            if time.time() - start_time > 5: 
                print("Time's Up")
                os._exit(1)
            time.sleep(0.001)
    
    
    t1 = Thread(target=ask)
    t2 = Thread(target=timing)
    t1.start()
    t2.start()
    t1.join()
    t2.join()