Home > Back-end >  Python while not true loops
Python while not true loops

Time:11-23

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.

CodePudding user response:

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.")

CodePudding user response:

while True:
    answer = ("Enter yes or no: ").lower()
    if answer in ["yes", "no"]:
        break
    print("Invalid answer.")
    # loop will repeat again
   
  • Related