0

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?"))
  • 4
    You had the correct idea that it needs a loop. A `while` loop will suffice here. If user correctly enters then use `break` – kuro May 15 '21 at 04:46
  • 3
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Gino Mempin May 15 '21 at 04:49

2 Answers2

1

Try a while True loop, and break when they answer right.

quinnmayo
  • 149
  • 1
  • 1
  • 5
1

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!
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    although unnecessary, you could group the conditions together for better read `while (answer not in answer_yes) and (answer not in answer_no) :` – blackraven May 15 '21 at 06:04