Logical OperatorsΒΆ
We can use the logical operators (or Boolean Operators) and
, or
, and not
to perform a certain kind of arithmetic on Boolean values. These rules for evaluating these operators are as follows:
When
and
appears between two Boolean values, it will evaluate toTrue
if and only if both Boolean values areTrue
. If either value isFalse
, then theand
operator will evaluate toFalse
.When
or
appears between two Boolean values, it will evaluate toTrue
if either of the Boolean values areTrue
. If both values areFalse
, then theor
operator will evaluate toFalse
.When
not
appears before a Boolean value, it will perform a logical negation, evaluating to the opposite Boolean value.
The cells below cover all of the possible cases that can arise from using these operators on Boolean values.
# Truth values for and operator
print(True and True)
print(True and False)
print(False and True)
print(False and False)
True
False
False
False
# Truth values for or operator
print(True or True)
print(True or False)
print(False or True)
print(False or False)
True
True
True
False
# Truth values for not operator
print(not True)
print(not False)
False
True
We can use the logical operators to combine basic conditional expressions into more complicated expressions.
x = 7
print( (x > 2) and (x < 9) )
print( (x > 2) and (x < 6) )
True
False
print( (x > 2) or (x < 6) )
print( (x > 9) or (x < 6) )
True
False
print( not (x < 9))
False