Exercise 0.1: Comparisons and Boolean operators: ten conditions to evaluate
The variables hold x = 6 and y = 10. Give the value of each condition: True or False.
Method: Python computes the arithmetic first, then the comparisons (==, !=, <, >, <=, >=), then not, then and, then or. A comparison with <= or >= includes the boundary value; a comparison with < or > excludes it.
- a) x < y
- b) x + 4 == y
- c) y != 10
- d) x >= 6
- e) x > 6
- f) x > 0 and y < 5
- g) x > 0 or y < 5
- h) not x > 8
- i) not (x < y and y < 12)
- j) x == 6 or y == 3 and x > 7
Show the solution
Answers
- a) True
- b) True: 6 + 4 is 10
- c) False
- d) True: 6 is included
- e) False: 6 is excluded
- f) False
- g) True
- h) True: not (6 > 8)
- i) False
- j) True: and runs before or
Replace x by 6 and y by 10, then apply the ranks: arithmetic, comparisons, not, and, or.
6 < 10 is True.
The arithmetic first: x + 4 = 10, then 10 == 10 is True.
== compares two values; a single = is an assignment, and Python refuses it inside a condition with a SyntaxError.
y holds 10, so y != 10, read « y is not equal to 10 », is False.
6 >= 6 is True: >= means greater than or equal to, so the boundary value 6 is included.
6 > 6 is False: > excludes the boundary value.
Pitfall: d) and e) differ for x = 6 only, the boundary value, which is why a test plan tries it.
x > 0 is True and y < 5 is False; and needs both sides True, so True and False is False.
or needs at least one side True: True or False is True.
not has a lower rank than a comparison: not x > 8 is not (6 > 8) = not False = True.
Inside the brackets, 6 < 10 is True and 10 < 12 is True, so the and gives True; then not True is False.
and runs before or: x == 6 or (y == 3 and x > 7) = True or (False and False) = True or False = True.
Pitfall: reading from left to right, (True or False) and False, which gives False.