Skip to main content

Section 25.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.
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:

Checkpoint 25.6.1.

    What does the code sample above do?
  • Produces an error message
  • Try running it!
  • Prints "That is a valid color." then "Done"
  • Correct
  • Prints "Done"
  • Try running it!
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 its 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 sides 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 25.6.3.

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.
You have attempted of activities on this page.