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:
x and y
is True
if both x
and y
are True
. Otherwise, and
produces False
.x or y
yields True
if either x
or y
or both is True
. Only if both operands are False
does or
yield False
.not x
yields False
if x
is True
, and vice versa.Look at the following example. See if you can predict the output. Then, Run to see if your predictions were correct:
Logical Operators
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 the following example. Again, before you run this, see if you can predict the outcome:
Compound Boolean Expressions
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 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 evaluate to booleans in order to yield proper results.