73.5k views
0 votes
Write a program that will prompt the user for some input, allow the user a certain amount of time to respond (e.g., 10 seconds), and if no response is provided within the allotted time, an appropriate timeout message printed on the screen.

User Brutos
by
4.5k points

1 Answer

7 votes

Answer:

  1. import time
  2. import threading
  3. response = None
  4. def checkAnswer():
  5. if response != None:
  6. time.sleep(10)
  7. return
  8. print("\\Input time out")
  9. thread1 = threading.Thread(target=checkAnswer)
  10. thread1.start()
  11. response = input("Enter your name: ")
  12. print("Welcome " + response)

Step-by-step explanation:

The solution code is written in Python 3.

Firstly import time and threading module (Line 1 -2). We are going to use sleep method from time module to set the interval time and also the Thread class from threading module to create a parallel running thread to check user response.

Let's initialize response variable with None (Line 4). Next, we define a function checkAnswer (Line 6). In the function, we set time interval 10 seconds using the sleep method and create an if condition to evaluate if the response is not None simply trigger the return statement or display the message input time out (Line 7- 10).

Next, we create a thread to run checkAnswer function (Line 12 - 13). While the thread1 is running, prompt the user to input name and display their name (Line 15 -16). Since the thread1 is running, if there is no response from user, the Input time out message will be displayed.

User Emanuel Fontelles
by
4.3k points