How to set an input time limit in Python

In this tutorial, we will learn how to set input time limit in Python. The user will get a specific time limit to enter the input.

Nowadays, developers need such type of mechanism to perform while developing applications or websites. Not only that, they use this to provide strong security such as in banks.

Most users face such type of situation while playing many kinds of games or other banking applications where users have to give their answers at a particular time.

As a Python developer, this language provides the easiest way to implement such a mechanism in our applications or websites due to its huge library and functionalities.

In Python, how can we set an input time limit?

First of all, we have to use the threading library of Python (you can see more about threading by clicking here).

From this library, we will use the Timer object of Python.

Now let’s see the code,

from threading import Timer

def exit():
    print("Times UP!!!!!!!!!!")
    
input_time=int(input("Set time limit: "))
t = Timer(input_time, exit)
t.start()
prompt = "You have %d seconds to choose the correct answer.................\n" % input_time
answer = input(prompt)
t.cancel()

Here, output depends upon input such as if we set a time limit of 2 seconds and give an answer in 2 seconds then it will come out correctly. whereas, if we set a time limit of 2 seconds and do nothing in that period then it will say Times UP!!!!!!!!!!.

First Output instance,

Set time limit: 2

You have 2 seconds to choose the correct answer.................

CodeSpeedy # if we enter here anything like this in 2 seconds then it will come out perfectly

>

Second Output example,

Set time limit: 2

You have 2 seconds to choose the correct answer.................

# if we do not do anything in 2 seconds then it will call exit() function as shown in above example and print as shown below

Times UP!!!!!!!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *