AQA 7517, section 4.1.1.5
Boolean operations combine or change True and False values. They let a program test more than one condition at once, such as "the user is logged in and has paid".
The four operations
NOT
NOT reverses a single value.
| A | NOT A |
|---|---|
False |
True |
True |
False |
AND
AND is true only when both inputs are true.
| A | B | A AND B |
|---|---|---|
False |
False |
False |
False |
True |
False |
True |
False |
False |
True |
True |
True |
OR
OR is true when at least one input is true.
| A | B | A OR B |
|---|---|---|
False |
False |
False |
False |
True |
True |
True |
False |
True |
True |
True |
True |
XOR
XOR (exclusive OR) is true when exactly one input is true, but not both.
| A | B | A XOR B |
|---|---|---|
False |
False |
False |
False |
True |
True |
True |
False |
True |
True |
True |
False |
The only difference between OR and XOR is the last row: with XOR, both being true gives False.
In Python
a = True
b = False
print(not a) # False
print(a and b) # False
print(a or b) # True
print(a != b) # True XOR: the two values are different
print(a ^ b) # True ^ also works as XOR on Booleans
Python has no xor keyword, so XOR is written as != or ^ on Boolean values.
Combining conditions
You can build bigger conditions by joining comparisons with Boolean operators:
age = 16
has_ticket = True
if age >= 12 and has_ticket:
print("Enter")
day = "Sat"
if day == "Sat" or day == "Sun":
print("Weekend")
if not (age >= 18):
print("Under 18")
Use brackets to make the order clear. When there are no brackets, NOT is done first, then AND, then OR.
Short-circuit evaluation: many languages stop as soon as the answer is known. In a and b, if a is False, then b is never checked. This is why x != 0 and 10 / x > 2 is safe: the division is skipped when x is 0.
Worked example
Task: a leisure centre lets someone swim if they are a member or have a day pass, and the pool is open.
is_member = False
has_day_pass = True
pool_open = True
can_swim = (is_member or has_day_pass) and pool_open
print(can_swim) # True
Evaluate it in order. The bracket first: False or True is True. Then True and True is True. Without the brackets, is_member or has_day_pass and pool_open would be worked out as is_member or (has_day_pass and pool_open), because AND comes before OR. For these particular values the answer is the same, but not in general. A member with no day pass and the pool closed would give True or (False and False), which is True, so they'd be let in to a closed pool.
Check yourself
What does True AND False give? And True OR False?
False and True respectively.
What is the difference between OR and XOR?
OR is true if either input or both inputs are true. XOR is true only if exactly one input is true, so it gives False when both are true.
Work out NOT (True AND False)
True AND False is False, and NOT False is True.
Write a condition that is true when n is less than 0 or greater than 100
n < 0 or n > 100