2

How do I make an offer/question expire in python, e.g.

import time
print("Hey there man.")
test = input()
if test == "Hey" or test == "Hi":
    print("Hey there dude.")
elif test == "Go away" or test == "Bye":
    print("Cya dude.")

How would I make this offer say I don't know only last 10 seconds before it ignores the if and elif statements and prints something completely new as in something similiar to...

import time
print("Hey there.")
test = input()
if test == "Hey" or test == "Hi":
    print("Hey there dude.")
elif test == "Go away" or test == "Bye":
    print("Cya dude.")
else time.sleep == >5:
    print("Nah your time has expired I'm out anyways.")
tripleee
  • 139,311
  • 24
  • 207
  • 268
  • Sorry? Could you tell us what offer do you want to expire? – TheRandomGuy Apr 01 '16 at 06:18
  • In this context, what is an "offer"? – jhoepken Apr 01 '16 at 06:19
  • Oh sorry just the whole command all together so after not saying anything for 10 seconds it would print something automatically and ignore the if and elif statement. – TOASTED PIE Apr 01 '16 at 06:20
  • This is an old article so it uses an earlier version of python to describe what is happening and as I am new to programming and only know of a few commands I don't exactly understand what I am reading. – TOASTED PIE Apr 01 '16 at 06:35

2 Answers2

3

Edit #2

Well scratch everything. I seriously over-complicated the problem. Sci Prog just posted a much simpler solution. Although I would change a few things like so.

import time

expires_in = 5 #in seconds    

start = time.time()
test = input("Hey there.\n") #\n is a newline character
end = time.time()

if end - start > expires_in:
    print("Nah your time has expired I'm out anyways.")
elif test == "Hey" or test == "Hi":
    print("Hey there dude.")
elif test == "Go away" or test == "Bye":
    print("Cya dude.")

Original Answer

This kind of does the trick. If it takes longer than the timeout period for the user to respond, than when they do get around to entering their input I print out a message saying it took to long.

However, because the input command pauses execution of the script until we get some input from the user, we cannot easily interject a message until they have entered something. There are two ways around this. 1) Instead of using input we use some lower level functions and we work with sys.stdout directly. 2) We multi-thread the script. Both of these methods are complicated, and are probably more work than you would want to get yourself into.

import time

def get_input():
    start_time = time.time()
    expires_in = 5 #in seconds
    got = ""

    while (time.time() - start_time < expires_in):
        if got: 
            print("you entered", got)
            return got
        got = input("enter something: ")

    print("You took to long")

Edit: The OP asked for an example that better follows what he was trying to accomplish, so here it is. I've added an explanation after the code as well.

import time

print("Hey there.")

def get_input():
    start_time = time.time()
    expires_in = 5 #in seconds
    user_input = ""

    while (time.time() - start_time < expires_in): #keep looping if the time limit has not expired
        if user_input:
            return user_input
        user_input = input()
    print("Nah your time has expired I'm out anyways.")

test = get_input()
if test == "Hey" or test == "Hi":
    print("Hey there dude.")
elif test == "Go away" or test == "Bye":
    print("Cya dude.")

time.time() will grab whatever the current time is. (returned as a big nasty number that represents the number of seconds since 0 BC).

Once we enter the while loop we don't have any user input yet so we can skip straight to the input statement. Then depending on how fast of a typer the user is we can have two outcomes.

a) The user responds in time. In this case we execute the while loop again. This time we enter the if user_input: if clause and we immediately return whatever the user inputted

b) The user does not respond in time. In this case we will not re-execute the while loop, and as a result we will continue to the print("Nah your time has expired I'm out anyways.") print statement.

I would like to note that it is important that we placed the input statement where we did. If we checked for user input after the user gave it to use, we would end up with the following scenario: The question expires, but the user still gives us some input. We see that the user gave us some input so we return the input. And then we never get a chance to tell the user the time has expired.

Also a nice little tip you could implement. You can make the input case-insensitive, by using input().lower() instead of input(). You would then have to change your if statements to be lower case as well. The user would then be able to type in either Hey or hey or something weird like hEy if they really wanted to.

Community
  • 1
  • 1
wp-overwatch.com
  • 6,475
  • 3
  • 34
  • 43
  • Since I am using python 3.x would I use raw_input or just input? – TOASTED PIE Apr 01 '16 at 06:40
  • input. Nice catch. I'll update my answer. – wp-overwatch.com Apr 01 '16 at 06:42
  • Thanks man. I'm glad you explained to me that if I wanted to do this it would be complicated instead of me just sitting there with an answer that some top notch guy posted and I wouldn't understand a thing, so thanks a lot for you input, but can I please ask one favour? substitute my example into your answer so I can learn to further understand how its is run and done. Thanks a lot man. – TOASTED PIE Apr 02 '16 at 23:55
  • It's the "got" part that kind of confuses me. – TOASTED PIE Apr 03 '16 at 01:32
  • got would be the same thing as test in your code. – wp-overwatch.com Apr 03 '16 at 01:38
  • While this will definitely enforce the input time limit, it would be even cooler if the loop automatically timed out after 5 seconds and printed the no input case. This might be possible by explicitly checking whether or not stdin has data... maybe? It seems like it will be tough to get around the hanging `input`. I'm going to up vote the question in the hope that one of the big Python people will offer a great solution. – Jared Goguen Apr 03 '16 at 04:40
  • For reference, [this question](http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) offers solutions for explicit timeouts :) – Jared Goguen Apr 03 '16 at 05:04
3

You can use datetime objects (from the module with the same name). Computing the differences gives a timedelta object.

Finally, you must test for the delay before checking for the answers.

from datetime import datetime
print("Hey there.")
dt1 = datetime.now()
test = input()
dt2 = datetime.now()
difference = dt2 - dt1  # this is a timedelta

if difference.seconds > 10 or difference.days > 0:
    print("Nah your time has expired I'm out anyways.")
elif test == "Hey" or test == "Hi":
    print("Hey there dude.")
elif test == "Go away" or test == "Bye":
    print("Cya dude.")

(runs in python 3, as specified in your question)

Of course, the .days part could be omitted, since it very unlikely that someone will wait that long :)

Sci Prog
  • 2,503
  • 1
  • 7
  • 17