How to set a timeout for Input

Doing the task you proposed isn't as easy as you might've guessed. It is easier to use the signal module to do this: (I have incorporated your code with a modified version of the answer I linked)

import signal, time

def TimedInput(prompt='', timeout=20, timeoutmsg = None):
    def timeout_error(*_):
        raise TimeoutError
    signal.signal(signal.SIGALRM, timeout_error)
    signal.alarm(timeout)
    try:
        answer = input(prompt)
        signal.alarm(0)
        return answer
    except TimeoutError:   
        if timeoutmsg:
            print(timeoutmsg)
        signal.signal(signal.SIGALRM, signal.SIG_IGN)
        return None

monsterhp = int(800)
y = 150
while monsterhp > 0:
    timeout = 4
    timeoutmsg = 'You ran out of time.'
    print(" ")
    prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
    answer = TimedInput(prompt, timeout, timeoutmsg)

    if answer == "attack":
        print("You strike the monster")
        time.sleep(1)
        monsterhp = monsterhp - y
        print("War Lord Health:", monsterhp)

Note: this will only work on all unix/mac system

You can change your while loop to this, for a improved version of your code:)

while monsterhp > 0:
        timeout = 4
        timeoutmsg = 'You ran out of time.'
        print(" ")
        prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
        answer = TimedInput(prompt, timeout, timeoutmsg)

        if answer == "attack":
            print("You strike the monster")
            time.sleep(1)
            monsterhp = monsterhp - y
            print("War Lord Health:", monsterhp)
        elif answer == None:
            print("The War Lord has killed you, you're now dead")
            print("Thanks for playing, \nGAME OVER")
            break