-1
door = input("Do you want to open the door? Enter yes or no: ").lower()

while door != "yes" and door != "no":
    print("Invalid answer.")
    door = input("Do you want to open the door? Enter yes or no: ").lower()

if door == "yes":
    print("You try to twist open the doorknob but it is locked.")
elif door == "no":
    print("You decide not to open the door.")

Is there an easier way to use the while loop for invalid answers? So I won't need to add that line after every single question in the program.

I tried def() and while true, but not quite sure how to use the them correctly.

fuwubuki
  • 1
  • 1
  • Show us the `def` approach you tried? It's a good idea to encapsulate the logic in a function (and you need to know how to write functions.) Also a `do while` might be good here. – Edward Peters Nov 22 '22 at 21:46
  • 1
    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) – Pranav Hosangadi Nov 22 '22 at 22:19

2 Answers2

2

One way to avoid the extra line:

while True
    door = input("Do you want to open the door? Enter yes or no: ").lower()
    if door in ("yes", "no"):
        break
    print("Invalid answer.")

Or if you do this a lot make a helper function.

def get_input(prompt, error, choices):
    while True:
        answer = input(f"{prompt} Enter {', '.join(choices)}: ")
        if answer in choices:
            return answer
        print(error)

Example usage:

door = get_input("Do you want to open the door?", "Invalid answer.", ("yes", "no"))
if door == "yes":
    print("You try to twist open the doorknob but it is locked.")
else:
    print("You decide not to open the door.")
001
  • 13,291
  • 5
  • 35
  • 66
-1
while True:
    answer = ("Enter yes or no: ").lower()
    if answer in ["yes", "no"]:
        break
    print("Invalid answer.")
    # loop will repeat again
   
John Gordon
  • 29,573
  • 7
  • 33
  • 58