There are three logical operators: and, or, and not. All three operators take boolean operands and produce boolean values. The semantics (meaning) of these operators is similar to their meaning in English:
Although you can use boolean operators with simple boolean literals or variables as in the above example, they are often combined with the comparison operators, as in this example. Again, before you run this, see if you can predict the outcome:
The expression x > 0 and x < 10 is True only if x is greater than 0 and at the same time, x is less than 10. In other words, this expression is True if x is between 0 and 10, not including the endpoints.
There is a very common mistake that occurs when programmers try to write boolean expressions. For example, what if we have a variable number and we want to check to see if its value is 5 or 6. In words we might say: βnumber equal to 5 or 6β. However, if we translate this into Python, number == 5 or 6, it will not yield correct results. The or operator must have a complete equality check on both sides. The correct way to write this is number == 5 or number == 6. Remember that both operands of or must be booleans in order to yield proper results.
Although most other programming languages do not allow this syntax, in Python, this syntax is allowed. Even though it is possible to use this format, you should not use it all the time. Instead, make multiple comparisons by using and or or.
Although this is legal Python syntax, the expression is incorrect. It will evaluate to true for all numbers that are either greater than 0 or less than 5. Because all numbers are either greater than 0 or less than 5, this expression will always be True.