Boolean Operators
A compound condition joins two or more comparisons with and or or, and not reverses a Boolean value. To evaluate one, you play the part of the computer: substitute the values the variables hold, work out each comparison as True or False, then combine those Boolean results using the rules for and, or and not.
The operators are not simply worked through left to right. Precedence decides the order: not is applied first, then and, then or. Two operators with the same precedence are worked left to right. Brackets override all of this, so anything inside brackets is worked out first, then not, then and, then or.
Imagine a game holds lives = 2, coins = 40 and power_up = False, and the program tests lives > 0 or coins >= 50 and power_up.
| Step | Expression | What happened |
|---|---|---|
| 1 | 2 > 0 or 40 >= 50 and False | substitute the values |
| 2 | True or False and False | each comparison becomes a Boolean value |
| 3 | True or False | and is done first |
| 4 | True | or is done last |
The answer is True. Working left to right would have given (True or False) and False, which is False, so the order really does change the answer.
Because not comes first, not power_up and coins > 20 becomes not False and True, then True and True, which is True.
Putting brackets around the or part forces a different order: (lives > 0 or coins >= 50) and power_up becomes (True or False) and False, then True and False, giving False.
Whenever and and or are mixed, add brackets so the grouping you intend is the grouping the computer uses, and so anyone reading the code sees it too. A common mistake is leaving brackets out and assuming the expression is read left to right, which silently changes the logic. Work one operator at a time, writing down the Boolean value of each part, so you can check the final answer.
OCR GCSE Computer Science · Boolean Operators