13.6. Complex Conditional Dangers¶
A common mistake when trying to use and
or 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:
- Produces an error message
- Try running it!
- Prints "That is a valid color." then "Done"
- Correct
- Prints "Done"
- Try running it!
What does the code sample above do?
Why does that happen? In English, we would think of “color equals” as talking about
“blue or green”. But in Python, the or
splits color == "blue"
from "green"
. Each
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 or
is False
,
and the value on the right is True
(according to Python), the final value of the expression
is True
.
color == "blue" | or | green |
False | or | True |
True |
The only way to get the logic we want, is to make sure both the left and right side of the or
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:
Warning
The items on both side of an and
or 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.