I was wondering how I can make a program with input of MAXIMUM 5 seconds(e.g he can send input after 2 seconds) in python I decided to do a SIMPLE game where you basically have to rewrite a word below 5 seconds. I know how to create input and make it wait EXACTLY 5 SECONDS, but what I want to achieve is to set maximum time of input to 5 seconds so if a user types an answer in let’s say 2 seconds he will go the next word. Could you tell me the way to achieve my goal. Thanks in advance!(I might respond the next day in case of getting an answer because I have to go sleep)
The code I have right now
for word in ["banana","earth","turtle","manchester","coctail","chicken"]:
# User gets maximum of 5 seconds to write the word,
# if he does it before 5 seconds pass ,he goes to next word (does not have to wait exactly 5 seconds, he
# can send input in e.g 2 seconds)
# if he does not do it in 5 seconds he loses game and it is finished
user_input = input(f"Type word '{word}': ")
#IF the word is correct go to next iteration
if(user_input==word):
continue
#If the word is incorrect finish the game
else:
print("You lost")
break
I tried to do it with threading.Timer() but it doesn’t work
import threading
class NoTime(Exception):
pass
def count_time():
raise NoTime
for word in ["banana","earth","turtle","manchester","coctail","chicken"]:
try:
#Create timer which raises exception after 5 seconds
timer = threading.Timer(5,count_time)
timer.start()
user_input = input(f"Type word '{word}': ")
#if timer hasn't lasted 5 seconds then destroy it in order to prevent unwanted exception
timer.cancel()
if user_input==word:
print("Correct")
else:
print("Incorrect, you LOSE!")
break
except NoTime:
print("You run out of time, you lose")
break
The error i get
Traceback (most recent call last):
File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1394, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\papit\OneDrive\Pulpit\Programming\Python Bro Course\Math\second\threading_training.py", line 7, in count_time
raise NoTime
NoTime