'Python time limit

I have a homework assignment to do and I really need a solution. I have been trying to do this since yesterday but I do not know how.

Program has to generate and print a letter or a number and then a user has to type it as quickly as possible and press ENTER. The game is over after 30 secs.

Well I do not know how to put time limit to a game. I was searching through stackoverflow and I did not find anything useful. Please help me.

**Here it is what I have done so far. I tried code from the answer by SYSS.STDER, but it does not quite work because when the 30 secs are over, the game should also be over, but here in this code the game is over when I type last character.

LOOP WILL NOT STOP UNTIL IT FINISHES AND WE DISCOVER THAT WE ARE PAST OUR DEADLINE. THE TASK NEEDS TO BE INTERRUPTED IN PROGRESS AS SOON AS THE TIME ELAPSES.

max_time =30
start_time = time.time()  # remember when we started
while (time.time() - start_time) < max_time:

    response = "a"      # the variable that will hold the user's response
    c = "b"             #the variable that will hold the character the user should type
    score = 0
    number = 0

    c = random.choice(string.ascii_lowercase + string.digits)
    print(c)
    number = number + 1

    response = input("Type a letter or a number: ") #get the user's response

    if response == c and (time.time() - start_time) < max_time:
         # if the response from the previous loop matches the character
         # from the previous loop, increase the score.
         score = score + 1


Solution 1:[1]

Since you're using Windows you can use the msvcrt.kbhit function to check for keypresses inside timing loops:

import msvcrt #### windows only ####
import os
import random
import string
import time

max_time = 15

def readch(echo=True):
    "Get a single character on Windows"
    ch = msvcrt.getch()
    while ch in b'\x00\xe0': # special function key?
        msvcrt.getch()       # get keycode & ignore
        ch = msvcrt.getch()
    if echo:
        msvcrt.putch(ch)
    return ch.decode()

def elapsed_time():
    global start_time
    return time.time() - start_time

number = 0
score = 0
start_time = time.time()  # initialize timer

while elapsed_time() < max_time:
    c = random.choice(string.ascii_lowercase + string.digits)
    print(c, end='')
    number += 1
    print("Type a letter or a number: ", end='')

    while elapsed_time() < max_time:
        if not msvcrt.kbhit():
            time.sleep(0.1) # don't hog processor
        else:
            response = readch(echo=False) # get the user's response
            if response == c:
                print(response) # only print if correct
                score += 1
                break
    else:
        print()

print()
print("Time's up")
print("You go  {} out of {}:".format(score, number))

Solution 2:[2]

A sample program to exit prime number function when Time limit has exceeded.

import math

from time import time

start_time = time() max_time = 2

def prime(n):

    for i in range(2, int(math.sqrt(n))):
        if(time() - start_time) > max_time:
            return "TLE"
        if n % i == 0:
            return False
    return True

print(prime(3900000076541747077))

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 martineau
Solution 2 Sri436