user2979879
user2979879

Reputation: 23

Using 'not in' and 'or' in a while loop

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

Answers (4)

Ahaan S. Rungta
Ahaan S. Rungta

Reputation: 2403

Try this.

while colour not in colours and not colour == "exit":

Upvotes: 0

Aaron Phalen
Aaron Phalen

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

John La Rooy
John La Rooy

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

user2555451
user2555451

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

Related Questions