0

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?

Michu
  • 69
  • 1
  • 5
  • 1
    I cant replicate your issue, it worked as expected for me is there an input that always gives this error? – BpY Feb 06 '20 at 11:10
  • No, sometimes it works, sometimes it hangs and I have to provide answer several times.. I have no idea what is wrong here.. – Michu Feb 06 '20 at 11:33
  • Maybe I should mention that I'm calling this function within another function. Does it change anything? – Michu Feb 06 '20 at 12:09
  • can you pose a [MRE](https://stackoverflow.com/help/minimal-reproducible-example) of the calling function? – BpY Feb 08 '20 at 13:01

0 Answers0