'How to create a timed input in python with a correct answer?
How would I create a program which asks the user for an input but if they dont respond with an answer within 5 seconds tells them that the time is up. But if the user gets the question right within the 5 seconds tells them that its right?
This is the code I have tried:
user_answer = None
def check():
if user_answer == 10:
print("Good")
return
time.sleep(5)
if user_answer != None:
return
print("Too Slow")
Thread(target = check).start()
user_answer = int(input("5+5 = "))
Solution 1:[1]
You check bring the check into in the same thread as int(input("5+5 = ")) and leave the check() for checking timeout only. If the user entered input or timeout, you can use os_exit(status_code) to terminate the entire application
import os
import time
from threading import Thread
timeout = 3
user_answer = None
def check_timeout():
time.sleep(timeout)
if user_answer != None:
return
print("\nToo Slow")
os._exit(0)
thread = Thread(target = check_timeout)
thread.start()
def check_anwser():
if user_answer == 10:
print("Good")
return
if user_answer != None:
print("Wrong")
return
user_answer = int(input("5+5 = "))
check_anwser()
os._exit(0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tax evader |
