I’m building a kind of question sequence as part of a program in Python 3.2. Basically, I ask a question and await an answer between two possibilities. If the given answer is not part of the two choices, I print a line and would like to re-ask the question until the correct input is given and then move on to the next question and repeat the same sequence.
Here is a snippet of code to maybe better explain myself:
colour = input("black or white?")
if colour in ["black", "white"]:
print("Thank you")
else:
print("Please choose one or the other")
So in other words, if the given answer is not black or white, I would like to print “Please choose one or the other”, and re-ask the question, as long as black or white is not given. Once black or white is given, I would want it to break out of the if statement so that I can ask another question in the same manner.
I’ve searched for how to do this but haven’t found anything useful. I’m guessing a while loop, but when I try it just spits out my last print string infinitely.
Keeping most of your code, wrap it in an infinite loop and break out of it when the input is what you are looking for.
Note, the test for membership uses a
tupleinstead of alistsince the choices won’t change, ie are immutable andin ("black", "white")makes this explicit.