Logical operators#

Comparison operators#

Recall that we introduced the “comparison operators” last week:

  • a>b returns True if a>b (a greater than b) and False otherwise.

  • a>=b returns True if a >= b (a greater than or equal tob ) and False otherwise.

  • a<b returns True if a<b (a less than b) and False otherwise.

  • a<=b returns True if a <= b (a less than or equal to b) and False otherwise.

  • a==b, equality test, returns True if a equals b and False otherwise.

  • a!=b, inequality test, returns True if a does not equal b and False otherwise.

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, returns True if a is False, and returns False if a is True.

  • a and b, returns True if both are True

  • a or b, returns True if either a or b are True.

There are therefore 3 logical operators that we introduce here not, and and or.