This question already has answers here:
Time-Limited Input? [duplicate]
(2 answers)
Closed 6 years ago.
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.")
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.
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 :)
Related
I'm a beginner in Python and I'm writing a code for a school project and ran into an early bug.
For some reason my if function won't run.
import time #imports computer time to program(buit in function)
count= 0
print(" Gymship") # center this
print("--------------------------------------") # this should go across the whole screen
print("Input a level to view the description or InputSign up to begin signing up for a card")
print("--------------------------------------------------------------------------")
print("Bronze")
time.sleep(1) # this wil pause the program for 1 second(for effect)
print("Silver")
time.sleep(1)
print("Gold")
time.sleep(1)
print("Platinum")
time.sleep(2)
print("-----------------------------------------------") # this should go across the whole screen
print("Sign up")
print(" ")
input()
if input == "Bronze":
print("Bronze")
print("--------------------------------------------")
print("You acquire a bronze card when you use two or less gym services")
print("2 Hours limit in the gym")
print("-------------------------------------")
print(input("Back to return to menu screen"))
count = count + 1
This is not correct:
input()
if input == "Bronze":
The way input() works is by returning a value. The name input refers to the function itself, so the function input will never equal the text "Bronze" unless you explicitly do something bad, like input = "Bronze" (it's bad because if you overwrite input, you'll no longer be able to access that function).
Instead, you should be using the returned value:
usr_input = input()
if usr_input == "Bronze":
Also, the line print(input("Back to return to menu screen")) is unnecessarily complicated; the print() will print whatever was returned by input(), but input() will display the "Back to return to menu screen" prompt without wrapping it in an if statement. So, input("Back to return to menu screen") is all you need. If you keep it the way you have it, if someone typed some text and then hit enter, the text would display again, because the print() is printing whatever that text was that the user typed.
You first need to assign a variable to the input and then check if the variable is equal to "Bronze"
Right now you are taking the input, but are not storing it anywhere. So the fixed code would be
user_input = input()
if user_input == "Bronze":
import cryptocode
import time
import sys
#Function to verify that the key is valid:
def check_valid(key):
message = cryptocode.decrypt(key, 'cryptocode is amazing')
if message == False:
#The key is incorrect!
return False
if float(message) >= time.time():
return True
else:
#The key has expired!
return False
userKeyInput = input("Please enter your product key.")
keyChecked = check_valid(userKeyInput)
if keyChecked == True:
print("You are good to go!")
if keyChecked == False:
print("You have either entered an invalid key or your time has expired. Sorry!")
sys.exit()
in this code we're creating a simple "trial product key". we're letting the user use the product for 2 hours. The password we will be using is cryptocode is amazing.
but I'm not able to grasp the significance of this statement in this program: if float(message) >= time.time(): , and what it is actually doing here
It would be appear to be the case that if successfully decrypted (i.e if 'cryptocode is amazing' was the correct password), then message (the content of key once decrypted) contains the time of expiration in float format. Hence, the line you're asking about converts it into float and compares it with the current time to check if it had already expired. (If the current time > expiration time, then the expiration time is in the past: the key had, indeed, already expired.)
In other words: there's an implicit assumption here that the key given to the user was the expiration time, encrypted.
I'm writing my first program - it's an idiom generator, which combines individual elements from lists of random verbs, nouns, and pronouns (that I have entered) in Madlibs style and generates a humorous expression. This is a simplified version of my source code:
baseFunction = True
def mainFunction() :
import random
quest = input("Which language do you want it in? Type 'French' or 'English'. ")
if quest == "French" or "french":
verb =
#list of verbs I have manually entered
noun =
#list of nouns I have manually entered
pronoun =
#list of pronouns I have manually entered
morenouns =
#list of nouns I have manually entered
phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
print(phrase)
print("Now, give it some meaning and use in the world!")
elif quest == "English" or "english":
verb =
#another list of verbs I have manually entered
noun =
#another list of nouns I have manually entered
pronoun =
#another list of pronouns I have manually entered
morenouns =
#another list of nouns I have manually entered
phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
print(phrase)
print("Now, invent some meaning for it and use it in the world!")
f8 = input("Do you want to make another one? Say 'yes' if you do. ")
if f8 == "yes" or "Yes":
mainFunction()
else:
print("Thanks for playing!")
else:
print("Didn't quite catch that. Try again! (say yes!)")
mainFunction()
def malif() :
ques = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
if ques == "yes" or "Yes":
mainFunction()
elif ques == "no" or "No":
print("Wrong answer. Try again! (say yes)")
malif()
else:
print("Didn't quite catch that. Say 'yes' or 'no'.")
while baseFunction :
malif()
mainFunction()
Essentially, I am asking the user whether they want to make an idiom, offering them a choice of language, generating the expression for them, and then asking them if they want to repeat the process. When I run the script in PyCharm, it runs the two functions in order (meaning, malif() first and then mainFunction(), as I have it at the end) but it does not pay any attention to my input (ex. if I say 'no' it runs the mainFunction anyway and will always do it in French even if I say 'English').
I used some of the tips discussed in this entry (Python - How to make program go back to the top of the code instead of closing). I think the problem lies calling the functions in their own definitions (ex. calling malif() if I answer 'no' to input 'ques', which is defined in malif() ). Yet, I have followed the tips discussed in the question that I linked and it is still not working the way that I want it to. Am I doing something wrong in formatting the code (ex. in terms of indentation) or if it is not obvious what I am doing wrong, is there a way for me to loop functions back to the beginning that was not suggested in the original question?
Thanks!
First some tips when you work with strings as input. Python will make the difference between caps and non-caps letter, thus a good way to deal with strings is to lower() them first (or upper(), ...):
Example:
ques = input("Enter Yes or No: ")
ques = ques.lower()
if ques == "yes":
# do something
elif ques == "no":
# do something else
else:
# raise error
Now I feel like your code is build in a funny way. A good habit is to separate the import from the functions, from the main program. The 2 first will be imported if the module (file) is imported, while the last one will be played when the file is executed. To do so, you can use this:
# -*- coding: utf-8 -*-
"""
docstring of the module
"""
# Imports
import random
import os
# Functions
def f():
return "Hello world"
# Main program
if __name__ == '__main__':
# Calling the function, taking the inputs and so on
In the main program, it's rather useful to deal with the possibility that an exception is raised. Moreover, if you use the cmd to display your program, the cmd will close immediately when an error is raised. This syntax is quite useful:
if __name__ == '__main__':
try:
# Do stuff
except:
import sys
print (sys.exc_info()[0])
import traceback
print (traceback.format_exc())
os.system("pause") # for windows, else easy way is to have an empty input to freeze the cmd
Now your code. I would rework it this way:
# -*- coding: utf-8 -*-
"""
Docstring
"""
# Imports
import random
import os
# Functions
def build_a_phrase(language) :
if language == "french":
verb = ["vendre", "atterir", "attaquer", "jeter"]
#list of verbs I have manually entered
noun = ["arbre", "poisson", "chien"]
#list of nouns I have manually entered
pronoun = ["un", "les"]
#list of pronouns I have manually entered
morenouns = ["chat", "oiseau"]
#list of nouns I have manually entered
choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
phrase = " ".join(choices) # Add a space between the words
return phrase
elif language == "english":
verb = ["...", "...", "..."]
#another list of verbs I have manually entered
noun = ["...", "...", "..."]
#another list of nouns I have manually entered
pronoun = ["...", "...", "..."]
#another list of pronouns I have manually entered
morenouns = ["...", "...", "..."]
#another list of nouns I have manually entered
choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
phrase = " ".join(choices) # Add a space between the words
return phrase
if __name__ == '__main__':
try:
# Parameters
available_language = ["french", "english"]
available_answers = ["yes", "no"]
# Safety implementation of an input
quest = ""
i = 0
while quest.lower() not in available_answers:
quest = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
i += 1
if i == 2: # number of tries
break
if quest.lower() == "no":
print ("I'm sure you meant yes.")
language = ""
i = 0
while language.lower() not in available_language:
language = input("Which language do you want it in? Type 'French' or 'English'.\n")
i += 1
if i == 2: # number of tries
break
while True:
sentence = build_a_phrase(language)
print (sentence)
print ("Now, give it some meaning and use in the world!")
f8 = ""
i = 0
while f8.lower() not in available_answers:
f8 = input("Do you want to make another one? Say 'yes' if you do. ")
i += 1
if i == 2: # number of tries
break
if f8.lower() == "no":
print("Thanks for playing!")
break
except:
import sys
print (sys.exc_info()[0])
import traceback
print (traceback.format_exc())
os.system("pause")
Hope you'll get a few good tricks from this answer, and some good habits :)
Not complete yet, when the input is wrong, an Error should be raised rather than waiting for the error resulting in the wrong input (i.e. a raise statement should be placed instead of the breaks)
So i created a while loop that the user input and an output is returned
choice = input()
while True:
if choice == "Mark":
print("Zuckerberg")
elif choice == "Sundar":
print("Pichai")
and i want to keep time so when i hit Facebook is going to keep time for FB and when i type Google is going to keep time for google like this
import time
choice = input()
while True:
if choice == "Facebook":
endb = time.time()
starta = time.time()
if choice == "google":
enda = time.time()
startb = time.time()
if choice == "Mark":
print("Zuckerberg")
elif choice == "Sundar":
print("Pichai")
if i make this like above when i get to print the elapsed time is going to print
the same number but is going to be minus instead of plus, and vice versa
elapseda = enda - starta
elapsedb = endb - startb
print(elapseda)
print(elapsedb)
How do i keep track of the time but be able to interact with my other input/outputs?
Thanks
##############################################################################
Edit: Sorry for making it not clear. What i meant by tracking time it that instead of print an output when you type a keyword is going to track time. This will be used to take the possession time of a sport match but meanwhile count other stats like Penalty Kicks and stuff. I cant post my code due to character limit but here is an idea:
while True:
choice = input()
if choice == "pk":
print("pk")
elif choice == "fk":
print("fk")
elif choice == "q":
break
and in there i should put possession time but meanwhile i want to interact with the others
In the while loop you could count seconds like so.
import time
a = 0
while True:
a = a + 1
time.sleep(1)
That would mean that a is about how many seconds it look to do the while loop.
I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using python 3.2
from random import choice
print("Welcome , let's get started")
input()
def word():
print('Humiliate')
a = input(':')
while a == 'abasement':
break
else:
word()
# --------------------------------------------------------- #
def word1():
print('Swelling')
a = input(':')
while a == 'billowing':
break
else:
word()
# ------------------------------------------------------------ #
wooo = [word(),word1()]
while 1==1:
print(choice(wooo))
is there any faster way of doing this and get real random? I tried classes but it seems harder than this. Also, is there any way I can make python not care about weather the input is capital letter or not?
To answer one part of your question ("is there any way I can make python not care about weather the input is capital letter or not?"): use some_string.lower():
>>> "foo".lower() == "foo"
True
>>> "FOO".lower() == "foo"
True
An this is to help you how you could improve the structure of your code:
import sys
from random import choice
WORDPAIRS = [('Humiliate', 'abasement'), ('Swelling', 'billowing')]
def ask():
pair = choice(WORDPAIRS)
while True:
answer = raw_input("%s: " % pair[0]).lower()
if answer == pair[1]:
print "well done!"
return
def main():
try:
while True:
ask()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == "__main__":
main()
It works like that:
$ python lulu.py
Swelling: lol
Swelling: rofl
Swelling: billowing
well done!
Humiliate: rofl
Humiliate: Abasement
well done!
Swelling: BILLOWING
well done!
Humiliate: ^C
$
wooo = [word, word1]
while 1:
print(choice(wooo)())
But in any case it will print you None, cause both of your functions return nothing (None).