Boolean Operators
not is the Boolean operator that reverses a Boolean value: whatever is True becomes False, and whatever is False becomes True. In Python it is always written in lower case.
Since the result is still a Boolean value, it can be used anywhere a condition is expected, such as the test of an if statement or the value stored in a variable.
| Value | not Value |
|---|---|
| True | False |
| False | True |
To reverse a whole comparison, write not in front of it. Putting the comparison in brackets, as in not (temperature > 20), makes it clear that not works on the finished result of the comparison rather than on the variable inside it.
Reversing an equality test gives exactly the same answer as using the not-equal operator. not (basket_items == 0) is logically equivalent to basket_items != 0: both give True when the basket contains at least one item, and both give False when the basket is empty.
If a variable already holds a Boolean value, not goes straight in front of it, with no comparison needed. if not ticket_paid: runs its block when ticket_paid is False, which is a neat way of testing that a task has not been completed or that something has not happened yet.
ticket_paid = False
print(not ticket_paid)
if not ticket_paid:
print("Please pay before you travel")Output:
True
Please pay before you travel
not never changes the value being tested; it only reverses the Boolean result.
OCR GCSE Computer Science · Boolean Operators