I have the following input function (based on the following answer https://stackoverflow.com/a/3041990/4992436)
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == "":
sys.exit()
elif choice in valid:
if valid[choice] == False:
sys.exit()
elif valid[choice] == True:
print("OK")
return False
else:
sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
The real problem is when I want to call this function later on, several times, e.g:
query_yes_no("First question, ok?\n")
query_yes_no("Second question, ok?\n")
query_yes_no("Third question, ok?\n")
Sometimes it's working as expected (output from terminal):
First question, ok?
[Y/n] y
OK
Second question, ok?
[Y/n] y
OK
Third question, ok?
[Y/n] y
OK
but sometimes I have to do multiple Enters (usually around 4-5) to finish it:
First question, ok?
[Y/n] y
y
y
y
OK
Second question, ok?
[Y/n] n
n
y
y
OK
Third question, ok?
[Y/n] y
OK
Why input() is not accepting my first choice? Why this function is still waiting for some answers, even if I provided such answer?