Search code examples
pythonloopsfor-loopwhile-loopuser-input

PYTHON - How to create a loop to prompt a specific answer


Today is my second day of coding, can anyone help me with this?

I'm writing a code to prompt user to answer yes, YES, y, Y or no, NO, n, N. If the user answer with another answer, the system should prompt user to answer again. Below is the current code I wrote.

However, I can't do it, can anyone help? Should I use what kind of loop?

print("Please answer the question below in y or n!!")

answer1 = input("Do you want apple?")

answer_yes = "y"
answer_no = "n"


if answer1 == answer_yes:
    print("Here you go!")
elif answer1 == answer_no:
    print("There are apples for you in the fridge!")
else:
    print(input("Do you want apple?"))

Solution

  • Here's one suggestion:

    print("Please answer the question below in y or n!!")
    answer = ''
    answer_yes = ['yes', 'YES', 'y', 'Y']
    answer_no = ['no', 'NO', 'n', 'N']
    
    while answer not in answer_yes and answer not in answer_no:
        answer = input("Do you want apple? ")
        if answer in answer_yes:
            print("Here you go!")
        elif answer in answer_no:
            print("There are apples for you in the fridge!")
    

    Output:

    Please answer the question below in y or n!!
    Do you want apple? n
    There are apples for you in the fridge!