The three Boolean operators (and, or, not) are used to compare Boolean values. Like comparison operators, they evaluate these expressions down to a Boolean value.
AND
The and operator always takes two Boolean values. The and operator evaluates an expression to True if both Boolean values are True; otherwise, it evaluates to False.
Examples
True and True -> True True and False -> False False and True -> False False and False -> False
OR
The or operator also takes two Boolean values. The or operator evaluates an expression to True if either of the two Boolean values is True.
True and True -> True True and False -> True False and True -> True False and False -> False
NOT
Unlike and and or, the not operator operates on only one Boolean value. The not operator simply evaluates to the opposite Boolean value
not True -> False not False -> True
Mixing Boolean and Comparison Operators
We can make more complicated expressions by combining our Boolean and Comparison Operators. We have to make sure that we evaluate down to either True or False.
Examples
(4 < 5) and (5<6)
-> True
(4 < 5) and (9<6)
-> False
(4 < 5) or (10<6)
-> True
The computer will evaluate the left expression first, and then it will evaluate the right expression. When it knows the Boolean value for each it will then evaluate the whole expression down to one.
Good and Bad Examples
Don’t use the actual words True and False as conditions or as comparison in the conditions.
Example:
if True: print("This will always run") if False: print("This will never run")
if some_condition == True: print("This isn't right") if some_condition: print("This is better")
The variable itself is the the boolean expression. It’s just extra code.
To check if something is False we can just use the NOT operator
if not some_condition: print("This statement is false")