how to set an input time limit in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how to set an input time limit in python?

is there any way i can add a time limit when asking a question using input in python? i want to ask the user a question but with a time limit of 15 seconds for the user to answer.

19th Feb 2021, 9:19 PM
kristine
6 Answers
+ 4
Yes, have u tried datetime module?
19th Feb 2021, 9:20 PM
Tomas Konecny
+ 2
You can use the time.time() function. It returns the time since Jan 1st 1970 in seconds! So, you can just do this : import time b = True #declare boolean so that code can be executed only if it is still True t1 = time.time() answer = input("Question") t2 = time.time() t = t2 - t1 if t > 15: print("You have run out of time!") b = False if b == True: #Rest of code I hope this helped! Happy programming :)
21st Feb 2021, 11:15 AM
TheCoder
+ 1
TheCoder thanks!
21st Feb 2021, 6:03 PM
kristine
0
Tomáš Konečný i haven't, i will check it out now.
19th Feb 2021, 9:35 PM
kristine
0
kristine you're welcome!
22nd Feb 2021, 12:04 AM
TheCoder