Reputation: 23
I'm trying to use a while loop to make sure an input is one I want. This bit of code is an example of what I'm trying to do. Is there any way to make this work?
Thank you.
colours=["red","black","blue"]
colour=raw_input("enter a colour")
while colour not in colours or colour!="exit":
colour=raw_input("enter a colour")
Upvotes: 1
Views: 110
Reputation: 2403
Try this.
while colour not in colours and not colour == "exit":
Upvotes: 0
Reputation: 421
Here is my solution
color_list = ["red", "black", "blue"]
while True:
color = str(raw_input("Enter a color: ")).strip()
if (color.lower() in color_list or color.lower() == 'exit'):
break
Upvotes: 0
Reputation: 304473
Writing it this way avoids the duplication of the prompt. The termination condition also reads more naturally.
while True:
colour = raw_input("enter a colour")
if colour in colours or colour == "exit":
break
Upvotes: -1
Reputation:
You need to use and
instead of or
:
while colour not in colours and colour!="exit":
Your current code will loop continually because colour
will always be either not in colours
or not equal to "exit"
.
Upvotes: 1