Python add a time limit and check whether they have acted





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I recently started learning python in school as my first language and received a homework task asking us to create a simple rock paper scissors game but with a twist (mine's an RPG) and I thought it would be good if I made it so you would have to answer withing a time limit. I checked a few other threads, but I wasn't sure how to implement that code into my program, so I decided to ask here. I'm very new to python so any simple answers would be preferred if possible.
Thank you advance!
EDIT: tomh1012 gave some advice and I took it but my timer still does not work. There isnt any error on anything, it simply does not work! Any help is greatly appreciated. Also, for whatever reason, my teacher hasn't taught us functions yet so I don't really understand them much.



while keepPlaying == "y":
while playerHealth > 0 and cpuHealth > 0:
time.sleep(0.75)
print ("You have " + str(playerHealth) + " health.")
print ("The enemy has " + str(cpuHealth) + " health.")
print ("Rock")
time.sleep(0.75)
print ("Paper")
time.sleep(0.75)
print("Scissors")
time.sleep(0.75)
startTime=time.process_time()
playerChoice = input ("Shoot!")
endTime=time.process_time()
elapsedTime = startTime - endTime
cpuChoice = (random.choice(options))
time.sleep(0.75)
print ("Your opponent chose " + cpuChoice)
if elapsedTime > 300:
print("You're too slow!")
elif playerChoice == "r" and cpuChoice == "s" or playerChoice == "p" and cpuChoice == "r" or playerChoice == "s" and cpuChoice == "p":
damageDealt = 10 * combo
combo = combo + 1
time.sleep(0.75)
print("You deal " + str(damageDealt) + " damage!")
cpuHealth = cpuHealth - damageDealt
enemyCombo = 1
elif cpuChoice == "r" and playerChoice == "s" or cpuChoice == "p" and playerChoice == "r" or cpuChoice == "s" and playerChoice == "p":
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
combo = 1
elif cpuChoice == playerChoice:
time.sleep(0.75)
print ("You both chose the same!")
else:
time.sleep(0.75)
print ("...")
time.sleep(1)
print("Thats not a choice...")
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
if cpuHealth <= 0:
print ("You win and gained 5 fans!")
fans = fans + 5
keepPlaying = input("Play again (y or n)")
enemyHeal
elif playerHealth <= 0:
print("You lose, sorry.")
keepPlaying = input("Play again (y or n)")









share|improve this question

























  • Have a look here and see if this helps: stackoverflow.com/a/15530613/9742036

    – Andrew McDowell
    Nov 23 '18 at 19:45











  • You can get time elapsed using the time module. Add import time to your code, then use t=time.clock() to take a record of the current cpu time. You can then subtract your first time from your second to get the amount of time elapsed between them. An if t1-t2==chosenTime: would then let you decide if they acted quick enough. Hope this helps

    – tomh1012
    Nov 23 '18 at 19:47











  • @tomh1012 Just tried this, right before the user inputs I get this error Warning (from warnings module): File "D:DownloadsRock paper scissors simple.py", line 37 startTime=time.clock() DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead and the timer does not work. What kind of result would I get if i minused the two times? Would it be seconds, minutes or a time stamp?

    – ElSponge
    Nov 23 '18 at 19:54













  • Check it: stackoverflow.com/questions/53167495/…

    – kantal
    Nov 23 '18 at 20:11











  • @ElSponge time.clock() will give you a number of milliseconds. That error is saying that time.clock() is outdated so you should use one of those other functions they've suggested. Really sorry but I can't help much with those new functions as I haven't learned much new python so time.clock() was the best I knew! If you look up those functions you should be able to work out what's new though

    – tomh1012
    Nov 23 '18 at 20:30


















1















I recently started learning python in school as my first language and received a homework task asking us to create a simple rock paper scissors game but with a twist (mine's an RPG) and I thought it would be good if I made it so you would have to answer withing a time limit. I checked a few other threads, but I wasn't sure how to implement that code into my program, so I decided to ask here. I'm very new to python so any simple answers would be preferred if possible.
Thank you advance!
EDIT: tomh1012 gave some advice and I took it but my timer still does not work. There isnt any error on anything, it simply does not work! Any help is greatly appreciated. Also, for whatever reason, my teacher hasn't taught us functions yet so I don't really understand them much.



while keepPlaying == "y":
while playerHealth > 0 and cpuHealth > 0:
time.sleep(0.75)
print ("You have " + str(playerHealth) + " health.")
print ("The enemy has " + str(cpuHealth) + " health.")
print ("Rock")
time.sleep(0.75)
print ("Paper")
time.sleep(0.75)
print("Scissors")
time.sleep(0.75)
startTime=time.process_time()
playerChoice = input ("Shoot!")
endTime=time.process_time()
elapsedTime = startTime - endTime
cpuChoice = (random.choice(options))
time.sleep(0.75)
print ("Your opponent chose " + cpuChoice)
if elapsedTime > 300:
print("You're too slow!")
elif playerChoice == "r" and cpuChoice == "s" or playerChoice == "p" and cpuChoice == "r" or playerChoice == "s" and cpuChoice == "p":
damageDealt = 10 * combo
combo = combo + 1
time.sleep(0.75)
print("You deal " + str(damageDealt) + " damage!")
cpuHealth = cpuHealth - damageDealt
enemyCombo = 1
elif cpuChoice == "r" and playerChoice == "s" or cpuChoice == "p" and playerChoice == "r" or cpuChoice == "s" and playerChoice == "p":
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
combo = 1
elif cpuChoice == playerChoice:
time.sleep(0.75)
print ("You both chose the same!")
else:
time.sleep(0.75)
print ("...")
time.sleep(1)
print("Thats not a choice...")
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
if cpuHealth <= 0:
print ("You win and gained 5 fans!")
fans = fans + 5
keepPlaying = input("Play again (y or n)")
enemyHeal
elif playerHealth <= 0:
print("You lose, sorry.")
keepPlaying = input("Play again (y or n)")









share|improve this question

























  • Have a look here and see if this helps: stackoverflow.com/a/15530613/9742036

    – Andrew McDowell
    Nov 23 '18 at 19:45











  • You can get time elapsed using the time module. Add import time to your code, then use t=time.clock() to take a record of the current cpu time. You can then subtract your first time from your second to get the amount of time elapsed between them. An if t1-t2==chosenTime: would then let you decide if they acted quick enough. Hope this helps

    – tomh1012
    Nov 23 '18 at 19:47











  • @tomh1012 Just tried this, right before the user inputs I get this error Warning (from warnings module): File "D:DownloadsRock paper scissors simple.py", line 37 startTime=time.clock() DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead and the timer does not work. What kind of result would I get if i minused the two times? Would it be seconds, minutes or a time stamp?

    – ElSponge
    Nov 23 '18 at 19:54













  • Check it: stackoverflow.com/questions/53167495/…

    – kantal
    Nov 23 '18 at 20:11











  • @ElSponge time.clock() will give you a number of milliseconds. That error is saying that time.clock() is outdated so you should use one of those other functions they've suggested. Really sorry but I can't help much with those new functions as I haven't learned much new python so time.clock() was the best I knew! If you look up those functions you should be able to work out what's new though

    – tomh1012
    Nov 23 '18 at 20:30














1












1








1








I recently started learning python in school as my first language and received a homework task asking us to create a simple rock paper scissors game but with a twist (mine's an RPG) and I thought it would be good if I made it so you would have to answer withing a time limit. I checked a few other threads, but I wasn't sure how to implement that code into my program, so I decided to ask here. I'm very new to python so any simple answers would be preferred if possible.
Thank you advance!
EDIT: tomh1012 gave some advice and I took it but my timer still does not work. There isnt any error on anything, it simply does not work! Any help is greatly appreciated. Also, for whatever reason, my teacher hasn't taught us functions yet so I don't really understand them much.



while keepPlaying == "y":
while playerHealth > 0 and cpuHealth > 0:
time.sleep(0.75)
print ("You have " + str(playerHealth) + " health.")
print ("The enemy has " + str(cpuHealth) + " health.")
print ("Rock")
time.sleep(0.75)
print ("Paper")
time.sleep(0.75)
print("Scissors")
time.sleep(0.75)
startTime=time.process_time()
playerChoice = input ("Shoot!")
endTime=time.process_time()
elapsedTime = startTime - endTime
cpuChoice = (random.choice(options))
time.sleep(0.75)
print ("Your opponent chose " + cpuChoice)
if elapsedTime > 300:
print("You're too slow!")
elif playerChoice == "r" and cpuChoice == "s" or playerChoice == "p" and cpuChoice == "r" or playerChoice == "s" and cpuChoice == "p":
damageDealt = 10 * combo
combo = combo + 1
time.sleep(0.75)
print("You deal " + str(damageDealt) + " damage!")
cpuHealth = cpuHealth - damageDealt
enemyCombo = 1
elif cpuChoice == "r" and playerChoice == "s" or cpuChoice == "p" and playerChoice == "r" or cpuChoice == "s" and playerChoice == "p":
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
combo = 1
elif cpuChoice == playerChoice:
time.sleep(0.75)
print ("You both chose the same!")
else:
time.sleep(0.75)
print ("...")
time.sleep(1)
print("Thats not a choice...")
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
if cpuHealth <= 0:
print ("You win and gained 5 fans!")
fans = fans + 5
keepPlaying = input("Play again (y or n)")
enemyHeal
elif playerHealth <= 0:
print("You lose, sorry.")
keepPlaying = input("Play again (y or n)")









share|improve this question
















I recently started learning python in school as my first language and received a homework task asking us to create a simple rock paper scissors game but with a twist (mine's an RPG) and I thought it would be good if I made it so you would have to answer withing a time limit. I checked a few other threads, but I wasn't sure how to implement that code into my program, so I decided to ask here. I'm very new to python so any simple answers would be preferred if possible.
Thank you advance!
EDIT: tomh1012 gave some advice and I took it but my timer still does not work. There isnt any error on anything, it simply does not work! Any help is greatly appreciated. Also, for whatever reason, my teacher hasn't taught us functions yet so I don't really understand them much.



while keepPlaying == "y":
while playerHealth > 0 and cpuHealth > 0:
time.sleep(0.75)
print ("You have " + str(playerHealth) + " health.")
print ("The enemy has " + str(cpuHealth) + " health.")
print ("Rock")
time.sleep(0.75)
print ("Paper")
time.sleep(0.75)
print("Scissors")
time.sleep(0.75)
startTime=time.process_time()
playerChoice = input ("Shoot!")
endTime=time.process_time()
elapsedTime = startTime - endTime
cpuChoice = (random.choice(options))
time.sleep(0.75)
print ("Your opponent chose " + cpuChoice)
if elapsedTime > 300:
print("You're too slow!")
elif playerChoice == "r" and cpuChoice == "s" or playerChoice == "p" and cpuChoice == "r" or playerChoice == "s" and cpuChoice == "p":
damageDealt = 10 * combo
combo = combo + 1
time.sleep(0.75)
print("You deal " + str(damageDealt) + " damage!")
cpuHealth = cpuHealth - damageDealt
enemyCombo = 1
elif cpuChoice == "r" and playerChoice == "s" or cpuChoice == "p" and playerChoice == "r" or cpuChoice == "s" and playerChoice == "p":
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
combo = 1
elif cpuChoice == playerChoice:
time.sleep(0.75)
print ("You both chose the same!")
else:
time.sleep(0.75)
print ("...")
time.sleep(1)
print("Thats not a choice...")
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
if cpuHealth <= 0:
print ("You win and gained 5 fans!")
fans = fans + 5
keepPlaying = input("Play again (y or n)")
enemyHeal
elif playerHealth <= 0:
print("You lose, sorry.")
keepPlaying = input("Play again (y or n)")






python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 21:31







ElSponge

















asked Nov 23 '18 at 19:41









ElSpongeElSponge

64




64













  • Have a look here and see if this helps: stackoverflow.com/a/15530613/9742036

    – Andrew McDowell
    Nov 23 '18 at 19:45











  • You can get time elapsed using the time module. Add import time to your code, then use t=time.clock() to take a record of the current cpu time. You can then subtract your first time from your second to get the amount of time elapsed between them. An if t1-t2==chosenTime: would then let you decide if they acted quick enough. Hope this helps

    – tomh1012
    Nov 23 '18 at 19:47











  • @tomh1012 Just tried this, right before the user inputs I get this error Warning (from warnings module): File "D:DownloadsRock paper scissors simple.py", line 37 startTime=time.clock() DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead and the timer does not work. What kind of result would I get if i minused the two times? Would it be seconds, minutes or a time stamp?

    – ElSponge
    Nov 23 '18 at 19:54













  • Check it: stackoverflow.com/questions/53167495/…

    – kantal
    Nov 23 '18 at 20:11











  • @ElSponge time.clock() will give you a number of milliseconds. That error is saying that time.clock() is outdated so you should use one of those other functions they've suggested. Really sorry but I can't help much with those new functions as I haven't learned much new python so time.clock() was the best I knew! If you look up those functions you should be able to work out what's new though

    – tomh1012
    Nov 23 '18 at 20:30



















  • Have a look here and see if this helps: stackoverflow.com/a/15530613/9742036

    – Andrew McDowell
    Nov 23 '18 at 19:45











  • You can get time elapsed using the time module. Add import time to your code, then use t=time.clock() to take a record of the current cpu time. You can then subtract your first time from your second to get the amount of time elapsed between them. An if t1-t2==chosenTime: would then let you decide if they acted quick enough. Hope this helps

    – tomh1012
    Nov 23 '18 at 19:47











  • @tomh1012 Just tried this, right before the user inputs I get this error Warning (from warnings module): File "D:DownloadsRock paper scissors simple.py", line 37 startTime=time.clock() DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead and the timer does not work. What kind of result would I get if i minused the two times? Would it be seconds, minutes or a time stamp?

    – ElSponge
    Nov 23 '18 at 19:54













  • Check it: stackoverflow.com/questions/53167495/…

    – kantal
    Nov 23 '18 at 20:11











  • @ElSponge time.clock() will give you a number of milliseconds. That error is saying that time.clock() is outdated so you should use one of those other functions they've suggested. Really sorry but I can't help much with those new functions as I haven't learned much new python so time.clock() was the best I knew! If you look up those functions you should be able to work out what's new though

    – tomh1012
    Nov 23 '18 at 20:30

















Have a look here and see if this helps: stackoverflow.com/a/15530613/9742036

– Andrew McDowell
Nov 23 '18 at 19:45





Have a look here and see if this helps: stackoverflow.com/a/15530613/9742036

– Andrew McDowell
Nov 23 '18 at 19:45













You can get time elapsed using the time module. Add import time to your code, then use t=time.clock() to take a record of the current cpu time. You can then subtract your first time from your second to get the amount of time elapsed between them. An if t1-t2==chosenTime: would then let you decide if they acted quick enough. Hope this helps

– tomh1012
Nov 23 '18 at 19:47





You can get time elapsed using the time module. Add import time to your code, then use t=time.clock() to take a record of the current cpu time. You can then subtract your first time from your second to get the amount of time elapsed between them. An if t1-t2==chosenTime: would then let you decide if they acted quick enough. Hope this helps

– tomh1012
Nov 23 '18 at 19:47













@tomh1012 Just tried this, right before the user inputs I get this error Warning (from warnings module): File "D:DownloadsRock paper scissors simple.py", line 37 startTime=time.clock() DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead and the timer does not work. What kind of result would I get if i minused the two times? Would it be seconds, minutes or a time stamp?

– ElSponge
Nov 23 '18 at 19:54







@tomh1012 Just tried this, right before the user inputs I get this error Warning (from warnings module): File "D:DownloadsRock paper scissors simple.py", line 37 startTime=time.clock() DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead and the timer does not work. What kind of result would I get if i minused the two times? Would it be seconds, minutes or a time stamp?

– ElSponge
Nov 23 '18 at 19:54















Check it: stackoverflow.com/questions/53167495/…

– kantal
Nov 23 '18 at 20:11





Check it: stackoverflow.com/questions/53167495/…

– kantal
Nov 23 '18 at 20:11













@ElSponge time.clock() will give you a number of milliseconds. That error is saying that time.clock() is outdated so you should use one of those other functions they've suggested. Really sorry but I can't help much with those new functions as I haven't learned much new python so time.clock() was the best I knew! If you look up those functions you should be able to work out what's new though

– tomh1012
Nov 23 '18 at 20:30





@ElSponge time.clock() will give you a number of milliseconds. That error is saying that time.clock() is outdated so you should use one of those other functions they've suggested. Really sorry but I can't help much with those new functions as I haven't learned much new python so time.clock() was the best I knew! If you look up those functions you should be able to work out what's new though

– tomh1012
Nov 23 '18 at 20:30












1 Answer
1






active

oldest

votes


















0














Here is a function that displays the given prompt to prompt a user for input. If the user does not give any input by the specified timeout, then the function returns None



from select import select
import sys

def timed_input(prompt, timeout):
"""Wait for user input, or timeout.

Arguments:
prompt -- String to present to user.
timeout -- Seconds to wait for input before returning None.

Return:
User input string. Empty string is user only gave Enter key input.
None for timeout.
"""
sys.stdout.write('(waiting %d seconds) ' % (int(timeout),))
sys.stdout.write(prompt)
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin], , , timeout)
if rlist:
return sys.stdin.readline().strip()
print()
return None





share|improve this answer
























  • This seems great! But I really wouldn't know how any of this works as Ive only had a few lessons. My teacher generally doesn't like us copying large blocks of code, but really, I wouldn't be able to adapt this. For now, I'll work on other parts of my program unless I get any new answers. Thanks a lot though! If we learn some of this soon maybe I'll come back to this and see if I can make any sense of it

    – ElSponge
    Nov 23 '18 at 23:09












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452189%2fpython-add-a-time-limit-and-check-whether-they-have-acted%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Here is a function that displays the given prompt to prompt a user for input. If the user does not give any input by the specified timeout, then the function returns None



from select import select
import sys

def timed_input(prompt, timeout):
"""Wait for user input, or timeout.

Arguments:
prompt -- String to present to user.
timeout -- Seconds to wait for input before returning None.

Return:
User input string. Empty string is user only gave Enter key input.
None for timeout.
"""
sys.stdout.write('(waiting %d seconds) ' % (int(timeout),))
sys.stdout.write(prompt)
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin], , , timeout)
if rlist:
return sys.stdin.readline().strip()
print()
return None





share|improve this answer
























  • This seems great! But I really wouldn't know how any of this works as Ive only had a few lessons. My teacher generally doesn't like us copying large blocks of code, but really, I wouldn't be able to adapt this. For now, I'll work on other parts of my program unless I get any new answers. Thanks a lot though! If we learn some of this soon maybe I'll come back to this and see if I can make any sense of it

    – ElSponge
    Nov 23 '18 at 23:09
















0














Here is a function that displays the given prompt to prompt a user for input. If the user does not give any input by the specified timeout, then the function returns None



from select import select
import sys

def timed_input(prompt, timeout):
"""Wait for user input, or timeout.

Arguments:
prompt -- String to present to user.
timeout -- Seconds to wait for input before returning None.

Return:
User input string. Empty string is user only gave Enter key input.
None for timeout.
"""
sys.stdout.write('(waiting %d seconds) ' % (int(timeout),))
sys.stdout.write(prompt)
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin], , , timeout)
if rlist:
return sys.stdin.readline().strip()
print()
return None





share|improve this answer
























  • This seems great! But I really wouldn't know how any of this works as Ive only had a few lessons. My teacher generally doesn't like us copying large blocks of code, but really, I wouldn't be able to adapt this. For now, I'll work on other parts of my program unless I get any new answers. Thanks a lot though! If we learn some of this soon maybe I'll come back to this and see if I can make any sense of it

    – ElSponge
    Nov 23 '18 at 23:09














0












0








0







Here is a function that displays the given prompt to prompt a user for input. If the user does not give any input by the specified timeout, then the function returns None



from select import select
import sys

def timed_input(prompt, timeout):
"""Wait for user input, or timeout.

Arguments:
prompt -- String to present to user.
timeout -- Seconds to wait for input before returning None.

Return:
User input string. Empty string is user only gave Enter key input.
None for timeout.
"""
sys.stdout.write('(waiting %d seconds) ' % (int(timeout),))
sys.stdout.write(prompt)
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin], , , timeout)
if rlist:
return sys.stdin.readline().strip()
print()
return None





share|improve this answer













Here is a function that displays the given prompt to prompt a user for input. If the user does not give any input by the specified timeout, then the function returns None



from select import select
import sys

def timed_input(prompt, timeout):
"""Wait for user input, or timeout.

Arguments:
prompt -- String to present to user.
timeout -- Seconds to wait for input before returning None.

Return:
User input string. Empty string is user only gave Enter key input.
None for timeout.
"""
sys.stdout.write('(waiting %d seconds) ' % (int(timeout),))
sys.stdout.write(prompt)
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin], , , timeout)
if rlist:
return sys.stdin.readline().strip()
print()
return None






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 23 '18 at 22:21









gammazerogammazero

348311




348311













  • This seems great! But I really wouldn't know how any of this works as Ive only had a few lessons. My teacher generally doesn't like us copying large blocks of code, but really, I wouldn't be able to adapt this. For now, I'll work on other parts of my program unless I get any new answers. Thanks a lot though! If we learn some of this soon maybe I'll come back to this and see if I can make any sense of it

    – ElSponge
    Nov 23 '18 at 23:09



















  • This seems great! But I really wouldn't know how any of this works as Ive only had a few lessons. My teacher generally doesn't like us copying large blocks of code, but really, I wouldn't be able to adapt this. For now, I'll work on other parts of my program unless I get any new answers. Thanks a lot though! If we learn some of this soon maybe I'll come back to this and see if I can make any sense of it

    – ElSponge
    Nov 23 '18 at 23:09

















This seems great! But I really wouldn't know how any of this works as Ive only had a few lessons. My teacher generally doesn't like us copying large blocks of code, but really, I wouldn't be able to adapt this. For now, I'll work on other parts of my program unless I get any new answers. Thanks a lot though! If we learn some of this soon maybe I'll come back to this and see if I can make any sense of it

– ElSponge
Nov 23 '18 at 23:09





This seems great! But I really wouldn't know how any of this works as Ive only had a few lessons. My teacher generally doesn't like us copying large blocks of code, but really, I wouldn't be able to adapt this. For now, I'll work on other parts of my program unless I get any new answers. Thanks a lot though! If we learn some of this soon maybe I'll come back to this and see if I can make any sense of it

– ElSponge
Nov 23 '18 at 23:09




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452189%2fpython-add-a-time-limit-and-check-whether-they-have-acted%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

"Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

Alcedinidae

Origin of the phrase “under your belt”?