Your feelings are correct. You see, Python's if statements do not work like an English setence. The second part of your if statement: ("Red" or "Yellow" or "Blue")
, is a boolean expression. The or
operator takes two values, and returns the first value which is true. In this case, since any non-empty string in Python is considered true in boolean terms, then your boolean expression returns "Red". This means that what your if statement is really saying is:
if line == "Red":
What you need to do is test line
against each value. While this could be done by going through each value and saying: if line == "Red" or line == "Blue"...
, Python was a much better way. Using the in
operator you can create an iterable with all the values you want to test line
against. Python will then test if line
is equal to any value in the iterable. In your case, using a tuple will be fine, but if you need to test line
against many more values, you should use a set()
instead:
if line in ("Red", "Yellow", "Blue"):
# do stuff
One last point is that line
could contain a newline. You can remove the newline by using .strip()
. So your finally solution would be:
if line.strip('\n') in ("Red", "Yellow", "Blue"):
# do stuff