Logical operators
Contents
Logical operators#
Comparison operators#
Recall that we introduced the “comparison operators” last week:
a>breturnsTrueifa>b(a greater than b) andFalseotherwise.a>=breturnsTrueifa >= b(a greater than or equal tob ) andFalseotherwise.a<breturnsTrueifa<b(a less than b) andFalseotherwise.a<=breturnsTrueifa <= b(a less than or equal to b) andFalseotherwise.a==b, equality test, returnsTrueifaequalsbandFalseotherwise.a!=b, inequality test, returnsTrueifadoes not equalbandFalseotherwise.
5 > 6, 5 >=6, 5 < 6, 5 <= 6, 5 == 6, 5 != 6
(False, False, True, True, False, True)
We can store the result of the comparison in a varible, e.g.
logicvar = 2==2 means that logicvar returns True when called and type(logicvar) returns <class 'bool'>.
logicvar = (2 == 2) # Using brackets to make order of operations clear
logicvar
True
Logical operators (on booleans)#
We introduced the boolean type last week: Boolean = a special type that can take two values: True or False. The comparison operators return a boolean object, always True or False, as we saw.
Now we introduce the logical operators. These are normally used on booleans to do logic operations (they can be used with other types, we won’t discuss that today).
For two given variables of type bool a and b we have
not a, returnsTrueifaisFalse, and returnsFalseifaisTrue.a and b, returnsTrueif both areTruea or b, returnsTrueif eitheraorbareTrue.
There are therefore 3 logical operators that we introduce here not, and and or.