简体   繁体   中英

How to continue asking user for input until it is considered valid?

My code is meant to ask a user to pick which household animal that is preferred. The answer should be either "cats" or "dogs" .

household_animal = (input("Which household animal do you prefer?"))
if household_animal in ("cat", "dog"):
    print("Thanks for your input on which household animal you prefer!")
else:
    print("This is not a household animal, please pick again.")

I am uncertain about how to make the program continue to ask for input until the user picks either "cat" or "dog" . If correct input is detected, it should no longer ask for more input.

How do I solve this?

You need to ask iteratively using a loop:

household_animal = input("Which household animal do you prefer?")
while household_animal not in ("cat", "dog"):
    print("This is not a household animal, please pick again.")
    # pick again
    household_animal = input("Which household animal do you prefer?")
print("Thanks for your input on which household animal you prefer!")

Explanation

Since you will need to keep asking for input until a suitable animal has been chosen, you should introduce some form of loop until that condition is met.

There are many ways to write such functionality, but what you are looking for is something such as the below.

household_animal = None
while household_animal not in ("cat", "dog"):
    if household_animal is not None:
      print ("This is not a household animal, please pick again.")

    household_animal = input ("Which household animal do you prefer?")

print ("Thanks for your input on which household animal you prefer!")

Note : The code will loop until household_animal is either "cat" or "dog" , and display an error message if the user has written something which is not one of the two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM