1

I need help to write a code that accepts input only if the user enters it within 5 seconds of asking for input, else prints out a message saying "Too late" and ending the program.

Clearly the algorithm I've used to solve the problem isn't right. There is no increment in time unless the user gives an input in the code given.

# code for accepting input only if entered within 5 seconds

print("Enter value: ")

sec = 0

for sec in range(0, 6):

    while sec==5:
        print("too late")
    time.sleep(1)
    sec += 1
    a=input()
eyllanesc
  • 190,383
  • 15
  • 87
  • 142
Justin_Time
  • 73
  • 1
  • 4
  • 5
    Possible duplicate of [Python 3 Timed Input](https://stackoverflow.com/questions/15528939/python-3-timed-input) / [User input with a timeout, in a loop](https://stackoverflow.com/questions/32193435/user-input-with-a-timeout-in-a-loop) – TrebledJ Jun 12 '19 at 16:29
  • Only because I didn't see it, you need to change ```print("Enter Value: ")``` to some kind of ```input``` (there are a few, and it depends on the python version you're using). In python 3 for example, it is common to do ```value = input("Enter Value: ")```. Just be careful because this converts whatever you enter to a string. – zerecees Jun 12 '19 at 16:31
  • Downvoter, care to explain? The OP provided a minimal reproducible example and a decent description of the problem. Yes, the provided code is utterly wrong, but that is not grounds for a downvote. – Leporello Jun 12 '19 at 16:34

2 Answers2

1

As a simple approach, you could maybe do something like this:

as input halts execution, the time elapsed is calculated upon entering the answer, and compared to the limit (here 5 seconds by default).
If within the time limit, the answer is returned for further processing, otherwise, too late is printed and None silently returned.

import time

def timed_acceptance(limit=5):
    start = time.time()
    a = input('you have 5 seconds:')
    end = time.time()
    if end - start < limit:
        return a
    else:
        print('too late')

timed_acceptance()
Reblochon Masque
  • 30,767
  • 8
  • 43
  • 68
  • this code waits for user to give input and then prints 'too late' if end-start>5. What i wanted was for the program to show a message 'to late' after 5 seconds and end, thereby preventing user from further entering any input. – Justin_Time Jun 12 '19 at 16:38
  • Yes, entering an answer triggers the calculation of the time elapsed, and a decision on the validity of the answer. – Reblochon Masque Jun 12 '19 at 16:39
0

The problem is that input blocks until there is input to be read. What you're looking for is what is known as non-blocking IO, that returns nothing if there isn't anything to read immediately. Here is a discussion on how to solve that in python: https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/

Henrik
  • 400
  • 1
  • 10