13.6. Complex Conditional Dangers¶
A common mistake when trying to use
or is to write things in the way we would
in English or in math class.
In natural (human) languages, if I want to say that the color of a car can be blue or green, I would only mention the car once: “The car can be blue or green.” If you try to do that in Python your program will not work as expected:
Why does that happen? In English, we would think of “color equals” as talking about
“blue or green”. But in Python, the
color == "blue" from
of those is evaluated on their own. Does
color == "blue"? No that is False. How about
"green". Is that True or False???
It turns out that any value that is not the number 0 or the empty string
"" is considered
True in Python. So
green counts as
True. Since the value on the left of
and the value on the right is
True (according to Python), the final value of the expression
|color == "blue"||or||green|
The only way to get the logic we want, is to make sure both the left and right side of the
are expressions that make sense on their own as logical expressions. We have to repeat the
color == `` part so that ``"green" is not evaluated on its own:
The items on both side of an
or MUST be logical expressions (True/False).
You can’t have something that looks like
... or "blue" or
... and 10 or that part
will just count as True.