Boolean operators
Boolean operators are used in expressions. The result of a Boolean expression is either True or False.
-
- AND - both sides of the AND operator must be True for the AND expression to be True.
- OR - at least one side of the OR operator must be True for the OR expression to be True.
- NOT - if the expression in front of NOT is True then the result of the NOT expression is False. If the expression in front of NOT is False then the result of the NOT expression is True.
If you have an expression with a mixture of NOTs, ANDs and ORs then there is an order of precedence, just like you always do multiplication before addition in arithmetic expressions. The order is:
NOT has the highest order of precedence.
AND has the second highest.
OR has the third highest.
So you always evaluate NOTs first, then ANDs and finally ORs in complex expressions. Just as with arithmetic and relational operators, expressions in brackets have the highest precedence so always use brackets to make expressions clear and to remove any doubt. If you have e.g. two ANDs in a row, you evaluate them left to right.
Q1. Predict your answers to the following expressions. Do not use Python just yet. For all questions:
s = 5
t = 10
u = 20
Boolean expression | True or False? |
s < u and u > t | |
t > s and s == 5 | |
s != u and t != s | |
5 = s or t != 20 | |
not s == 5 | |
not u > 10 | |
s > 10 or u <= 20 | |
u != 10 or t == 10 | |
t >= 5 and s == 10 or u < 10 | |
s >= 5 and not t == 10 | |
not u <= 20 and t < 50 | |
s == 5 and t == 5 and u == 20 | |
not s != 5 and not t != 5 | |
(s != 5 or t == 10) and u != 30 | |
(t == 10) or (u == 20) | |
(not s != 10) or (not t != 10) | |
u == 20 and not t < 30 | |
s > 1 or (u = 20 and t <= 10) | |
(not s != 10) or (not t == 10) | |
(not t != 10) and (not s != 5) |
Q2. When you have completed the table above, compare your answers with a friend's answers. Then use the Python shell to check your answers.