ICS3U Computer Science • Ontario Grade 11

Corrected exercises: selection, if, elif, else and Boolean logic (ICS3U)

Exercises: selection, if, elif, else and Boolean logic (ICS3U)

Name: Class: Date:

Solutions

Suggested time: 2 h 30 · No calculator · 11 exercises
https://www.letuteurscientifique.ca/en/exercices/ics3u-selection-boolean-logic

These ten corrected exercises, preceded by a list of direct calculations, cover the second chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: Boolean values and expressions, the comparison operators (equal to, not equal to, greater than, less than, greater than or equal to, less than or equal to), the Boolean operators and, or and not with their truth tables and De Morgan's laws, and the selection structure: if, if else, the cascade if, elif, else and nested if statements, tested on their boundary values.

What the set covers, the traps it targets

The code is in Python 3; truth tables, traces and test plans are reasoned the same way in any language, and a line of the solutions says where Java behaves differently.

Exercise 0.1 evaluates ten conditions. By the end, you can build a truth table and check De Morgan's laws on it (exercise 1), trace a cascade and explain why only one branch runs, on a triangle classifier (exercise 2), see why choice == 1 or 2 is always true and correct it (exercise 3), put each boundary on the right side with < or <=, at a baggage counter (exercise 4), and tell separate if statements from a cascade, on the warnings of a phone battery (exercise 5). Part B rewrites the nested if statements of a climbing wall rule as one condition, then negates it (exercise 6), finds an unreachable branch in a UV index app (exercise 7), corrects five statements (exercise 8), runs a test plan on a greenhouse controller and counts the tests that fail (exercise 9), and writes a time-of-use electricity price program from its specification (exercise 10).

The thread of the set: a condition is a value, True or False, computed before the if decides; in a cascade only the first branch whose condition is True runs, so each test is read knowing that every test above it was False. Five traps are named in the solutions: (1) forgetting that a cascade stops at its first True branch, so that the order of the tests is the logic, exercises 2, 5, 7 and 8; (2) writing < where the rule includes the boundary, or <= where it excludes it, which changes the result for the boundary value only, exercises 0.1, 2, 4, 6, 8, 9 and 10; (3) writing x == 1 or 2, which is always true, exercises 3 and 8; (4) negating a compound condition without exchanging and with or, against De Morgan's laws, exercises 0.1, 1, 6 and 8; (5) separate if statements where a single message is expected, so that several branches run, exercises 5 and 9. The rank of and above or, which decides how a condition without brackets is read, comes back in exercises 0.1, 6 and 10.

No calculator is needed: every condition, every trace and every truth table is worked out by hand, as on a unit test.

  • 11 corrected exercises • 110 points • 150 minutes
  • Self-checking, 101 answers
  • No calculator
Start exercise 0.1 The chapter sheet
Print

Print the homework or the solutions

The homework without solutions, one exercise per page, and the solutions on their own: it comes with your free space. An email is enough, no password, and you come back here.

Create my free space

Already have one? Sign in

Course recap

  • • Comparison operators: == (equal to), != (not equal to), <, >, <= (less than or equal to), >= (greater than or equal to). A comparison gives True or False. A single = is an assignment.
  • • and is True when both sides are True; or is True when at least one side is True; not gives the opposite.
  • • Order in a condition: arithmetic, then comparisons, then not, then and, then or.
  • • De Morgan's laws: not (a and b) is (not a) or (not b); not (a or b) is (not a) and (not b).
  • • In a cascade if, elif, else, only the first branch whose condition is True runs; the else runs when every test above it was False.
  • • Separate if statements are each tested: several of them can run for one input.
  • • Each side of or is a full condition: x == 1 or x == 2.
  • • The opposite of < is >=, the opposite of <= is >. Test every boundary: just below it, on it, just above it.

Calculations: conditions to evaluate

Exercise 0.1: Comparisons and Boolean operators: ten conditions to evaluate

10 answers to check

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

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
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.

a)

6 < 10 is True.

b)

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.

c)

y holds 10, so y != 10, read « y is not equal to 10 », is False.

d)

6 >= 6 is True: >= means greater than or equal to, so the boundary value 6 is included.

e)

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.

f)

x > 0 is True and y < 5 is False; and needs both sides True, so True and False is False.

g)

or needs at least one side True: True or False is True.

h)

not has a lower rank than a comparison: not x > 8 is not (6 > 8) = not False = True.

i)

Inside the brackets, 6 < 10 is True and 10 < 12 is True, so the and gives True; then not True is False.

j)

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.

Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.

Part A: the basics (/50)

Exercise 1: Truth tables: and, or, not and De Morgan's laws

9 answers to check

A Boolean variable holds True or False. A truth table lists every combination of values of the variables, one combination per row, and gives the value of each expression on every row. The table below starts the truth table of two variables A and B, with its rows in the usual order.

The rules: A and B is True only when A and B are both True; A or B is True when at least one of them is True; not A is the opposite of A.

ABA and BA or Bnot (A and B)(not A) or (not B)TrueTrueTrueFalseFalseTrueFalseFalseTruth table of A and B, to complete
  • a) How many rows does the truth table of two Boolean variables have? How many rows for three variables A, B and C?
  • b) Complete the columns A and B and A or B. On how many rows is A and B True? On how many rows is A or B True?
  • c) Complete the columns not (A and B) and (not A) or (not B). Give the value of each one on the row where A is True and B is False. What do the two complete columns show?
  • d) A student writes (not A) and (not B) in place of not (A and B). On how many of the four rows do these two expressions give different values?
  • e) Which expression always has the same value as not (A or B)?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 4 rows; 8 rows for three variables
  • b) A and B: 1 row; A or B: 3 rows
  • c) True and True; the two columns are identical on all four rows
  • d) 2 rows: A True with B False, and A False with B True
  • e) (not A) and (not B)

The method: fill one column at a time, from left to right, each column computed from the columns already filled. The complete table is below.

a)

Each variable has two values, and each new variable doubles the number of combinations: 2 × 2 = 4 rows for A and B, 2 × 2 × 2 = 8 rows for A, B and C.

b)

A and B is True on the first row only, where both are True: 1 row.

A or B is False on the last row only, where both are False, so it is True on 3 rows.

c)

On the row A = True, B = False: A and B is False, so not (A and B) is True.

not A is False and not B is True, so (not A) or (not B) is False or True = True.

The two columns read False, True, True, True: they are identical on every row. This is one of De Morgan's laws: not (A and B) has the same value as (not A) or (not B).

d)

(not A) and (not B) reads False, False, False, True: it is True only when both variables are False.

not (A and B) reads False, True, True, True. The two differ on the two middle rows, where one variable is True and the other is False.

Pitfall: passing not through the brackets without turning and into or. The negation of an and is an or.

e)

The second law of De Morgan: not (A or B) has the same value as (not A) and (not B). Both columns read False, False, False, True.

To negate a compound condition, negate each part and exchange the operator: and becomes or, or becomes and.

ABA and BA or Bnot (A and B)(not A) or (not B)TrueTrueTrueTrueFalseFalseTrueFalseFalseTrueTrueTrueFalseTrueFalseTrueTrueTrueFalseFalseFalseFalseTrueTrueThe two last columns are identical

Exercise 2: A cascade runs one branch: classifying a triangle

10 answers to check

Three whole lengths are the sides of a triangle only if each one is shorter than the sum of the other two. A triangle is equilateral when its three sides are equal, isosceles when at least two sides are equal, and scalene when no two sides are equal. So an equilateral triangle is also isosceles, and the program must print the more precise name.

Python
a = int(input('Side a: '))                    # line 1
b = int(input('Side b: '))                    # line 2
c = int(input('Side c: '))                    # line 3
if a + b <= c or a + c <= b or b + c <= a:    # line 4
    print('Not a triangle')                   # line 5
elif a == b and b == c:                       # line 6
    print('Equilateral')                      # line 7
elif a == b or b == c or a == c:              # line 8
    print('Isosceles')                        # line 9
else:                                         # line 10
    print('Scalene')                          # line 11
  • a) What does the program print for the sides 7, 7, 7? For 7, 7, 10?
  • b) For 7, 7, 7, the condition on line 8 is True as well. Why is Isosceles not printed too?
  • c) What does the program print for 4, 6, 10, and what is the value of 4 + 6 <= 10? A classmate writes line 4 with < in place of each <=. What does that version print for 4, 6, 10?
  • d) A student exchanges the two elif tests, each with its print line, so that the test of line 8 comes before the test of line 6. What does this version print for 7, 7, 7? Can it ever print Equilateral?
  • e) In the original program, how many of the tests on lines 4, 6 and 8 does Python evaluate for 5, 8, 11? For 7, 7, 7?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Equilateral; Isosceles
  • b) Only the first branch whose condition is True runs; the rest of the chain is skipped
  • c) Not a triangle, since 4 + 6 <= 10 is True; with <, Scalene
  • d) Isosceles; no, never
  • e) 3 tests for 5, 8, 11; 2 tests for 7, 7, 7

In a chain if, elif, else, Python tests the conditions from the top. The first condition that is True runs its branch, then Python jumps past the end of the chain: the tests below it are not evaluated. The table below traces the four inputs of the exercise.

a)

7, 7, 7. Line 4: 7 + 7 <= 7 is False, and so are the two other sums, so the or gives False. Line 6: a == b and b == c is True, and the program prints Equilateral.

7, 7, 10. Line 4: 14 <= 10, 17 <= 7 and 17 <= 7 are False. Line 6: b == c is False, so the and is False. Line 8: a == b is True, so the or is True: Isosceles.

b)

Line 6 was True, so its branch ran and the chain ended there: line 8 is not evaluated for 7, 7, 7.

The order of the tests carries the logic: line 8 can test « at least two equal sides » because it is reached only when the triangle is not equilateral.

c)

4 + 6 <= 10 is 10 <= 10, True: line 5 prints Not a triangle. Sticks of 4, 6 and 10 cm lie flat along one line and enclose no area.

With <, 10 < 10 is False, and so are 4 + 10 < 6 and 6 + 10 < 4. The chain goes on, no two sides are equal, and the else prints Scalene, for a triangle that does not exist.

Pitfall: < in place of <= changes the result in one case only, when one side equals the sum of the two others. Only a test on that boundary reveals it.

d)

Exchanged, the test a == b or b == c or a == c comes first. For 7, 7, 7 it is True, so the program prints Isosceles and stops.

Every equilateral triangle passes the isosceles test first, so the Equilateral branch can never run: it is unreachable. Two correct conditions in the wrong order make a wrong program.

e)

5, 8, 11: line 4 is False (13 <= 11, 16 <= 8 and 19 <= 5 are all False), line 6 is False, line 8 is False. 3 tests, then the else prints Scalene.

7, 7, 7: line 4 is False, line 6 is True. 2 tests; line 8 is skipped.

SidesLine 4Line 6Line 8Printed7, 7, 7FalseTruenot testedEquilateral7, 7, 10FalseFalseTrueIsosceles4, 6, 10Truenot testednot testedNot a triangle5, 8, 11FalseFalseFalseScaleneTests evaluated for each input

Exercise 3: The condition choice == 1 or 2 is always true

7 answers to check

A game shows a menu of four choices. Choices 1 and 2 must both start a game, a new one or a saved one; choice 3 opens the settings and choice 4 quits.

Python
print('1 New game  2 Load game  3 Settings  4 Quit')   # line 1
choice = int(input('Choice: '))                        # line 2
if choice == 1 or 2:                                   # line 3
    print('Starting a game')                           # line 4
elif choice == 3:                                      # line 5
    print('Opening the settings')                      # line 6
else:                                                  # line 7
    print('Goodbye')                                   # line 8
  • a) The user types 3. What does the program print after the menu?
  • b) How does Python group the condition choice == 1 or 2?
  • c) For how many of the four choices 1, 2, 3 and 4 does line 4 run? Can line 6 or line 8 ever run?
  • d) Which line 3 gives the behaviour the menu describes?
  • e) Python also accepts the chained comparison 1 <= choice <= 2. For whole-number choices, does it give the same decisions as the corrected line 3? What does the corrected program print if the user types 0?

Type your answers, the page tells you right or wrong 0/7

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Starting a game
  • b) (choice == 1) or 2
  • c) 4 choices; no, lines 6 and 8 never run
  • d) if choice == 1 or choice == 2:
  • e) Yes, the same decisions; 0 prints Goodbye

Read the condition the way Python reads it, by the ranks of the operators: == has a higher rank than or, so the comparison is made first, and or joins what is on its two sides.

a)

For 3: choice == 1 is False, so the condition is False or 2.

or gives a true result as soon as one side counts as true, and in a condition Python counts any number other than 0 as true. 2 counts as true, so line 4 runs: Starting a game.

Pitfall: reading the line as English, « choice is 1 or 2 ». Python reads (choice == 1) or 2.

b)

(choice == 1) or 2: the comparison first, then or, whose right side is the number 2 alone, never compared with choice.

c)

The right side, 2, makes the condition true whatever choice holds: line 4 runs for all 4 choices.

Lines 5 to 8 can never run: the elif and the else are dead code, and no error message warns about it.

In Java, if (choice == 1 || 2) does not compile: || needs two boolean operands and 2 is an int, so the compiler catches the bug.

d)

Each side of or must be a complete comparison: if choice == 1 or choice == 2:.

choice == 1 and choice == 2 is never True, since one variable cannot hold 1 and 2 at the same time. choice == (1 or 2) compares choice with the value of 1 or 2, which Python computes as 1, so choice 2 would not start a game.

e)

Yes. For a whole number, 1 <= choice <= 2 means choice >= 1 and choice <= 2, which holds for 1 and 2 only, the same two values. Java has no chained comparison; it writes choice >= 1 && choice <= 2.

For 0, the tests of lines 3 and 5 are False, and the else prints Goodbye: the program quits on a typing mistake. A safer menu tests elif choice == 4 for Goodbye and keeps the else for a message such as Invalid choice.

Exercise 4: Boundaries: < or <= at the baggage counter

8 answers to check

An airline weighs each checked bag, and the scale shows the weight to the tenth of a kilogram. Its rules: up to 23 kg included, the bag is accepted without a fee; above 23 kg and up to 32 kg included, it is accepted with an overweight fee of 100 dollars; above 32 kg, it is refused and must be repacked.

Python
weight = float(input('Weight of the bag (kg): '))   # line 1
if weight < 23:                                     # line 2
    print('Accepted, no fee')                       # line 3
elif weight < 32:                                   # line 4
    print('Overweight fee: 100 dollars')            # line 5
else:                                               # line 6
    print('Refused: repack the bag')                # line 7
  • a) What does the program display for 22.9 kg? For 23.0 kg? For 32.0 kg?
  • b) How many of these three answers contradict the rules?
  • c) Give, as an interval, the set of weights for which the program as written displays the overweight fee.
  • d) Correct lines 2 and 4. Give the interval of weights that pay the fee after the correction.
  • e) The scale can show any weight from 0.1 kg to 50.0 kg, in steps of 0.1 kg. For how many of these readings does the original program give a wrong message? Which three readings test the 23 kg boundary in a test plan?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
Weights that pay the fee, as written ,
d)
Weights that pay the fee, corrected ,
e)
Show the solution

Answers

  • a) Accepted, no fee; Overweight fee: 100 dollars; Refused: repack the bag
  • b) 2: 23.0 kg and 32.0 kg
  • c) {w ∈ ℝ | 23 ≤ w < 32}, the interval [23, 32)
  • d) {w ∈ ℝ | 23 < w ≤ 32}, the interval (23, 32]
  • e) 2 readings; 22.9, 23.0 and 23.1

A boundary decides which branch receives the value written in the rule: « up to 23 kg included » is weight <= 23, and its opposite, « above 23 kg », is weight > 23. The corrected program is below.

a)

22.9 < 23 is True: Accepted, no fee.

23.0 < 23 is False and 23.0 < 32 is True: Overweight fee: 100 dollars, although the rules make a bag of 23 kg free.

32.0 < 23 and 32.0 < 32 are False: the else displays Refused: repack the bag, although the rules accept 32 kg with the fee.

b)

2 answers out of 3 contradict the rules: 23.0 kg and 32.0 kg, the two boundary values.

Pitfall: testing only with typical weights such as 18 kg, 27 kg and 40 kg, which all get the right message. Only the boundary values expose < in place of <=.

c)

Line 5 runs when line 2 is False and line 4 is True: weight >= 23 and weight < 32, that is {w ∈ ℝ | 23 ≤ w < 32}, the interval [23, 32): 23 is in it, 32 is not.

d)

Line 2 becomes if weight <= 23: and line 4 becomes elif weight <= 32:.

The fee is now paid when weight > 23 and weight <= 32: {w ∈ ℝ | 23 < w ≤ 32}, the interval (23, 32]. Both ends have changed sides, as the rules say.

e)

The two programs disagree only on a reading equal to a boundary, 23.0 or 32.0: 2 readings out of 500.

A boundary is tested by three readings: just below it, on it, just above it. For 23 kg, with a scale to the tenth: 22.9, 23.0 and 23.1.

Python
weight = float(input('Weight of the bag (kg): '))
if weight <= 23:
    print('Accepted, no fee')
elif weight <= 32:
    print('Overweight fee: 100 dollars')
else:
    print('Refused: repack the bag')
no feefeerefused23.0: fee32.0: refusedAs written: weight < 23, then weight < 32no feefeerefused23.0: no fee32.0: feeThe rules: weight <= 23, then weight <= 32

Exercise 5: Separate if statements: three warnings for one battery

10 answers to check

A phone must show a single warning, the most urgent one that applies: at 5 % or less, Shutting down soon; at 20 % or less, Low battery: saver mode on; at 50 % or less, Consider charging; above 50 %, no warning. The battery level is a whole number from 0 to 100.

Python
battery = int(input('Battery level (%): '))      # line 1
if battery <= 5:                                 # line 2
    print('Shutting down soon')                  # line 3
if battery <= 20:                                # line 4
    print('Low battery: saver mode on')          # line 5
if battery <= 50:                                # line 6
    print('Consider charging')                   # line 7
  • a) How many lines does the program print for 4 %? For 15 %? For 35 %? For 80 %?
  • b) For 4 %, which message appears first on the screen?
  • c) Lines 4 and 6 are rewritten with elif. How many lines are printed now for 4 % and for 15 %, and which message for 15 %?
  • d) A classmate writes the elif chain in the order 50, 20, 5: if battery <= 50 first, then elif battery <= 20, then elif battery <= 5. What does this version print for 4 %?
  • e) Back to the original program, with its three separate if statements. For how many of the 101 levels from 0 to 100 does it print more than one line?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 3; 2; 1; 0
  • b) Shutting down soon
  • c) 1 line for each; Low battery: saver mode on
  • d) Consider charging
  • e) 21 levels, from 0 to 20

Separate if statements are tested one after the other, each on its own, and every one whose condition is True runs. A cascade with elif stops at the first True condition. The table below compares the two versions; the corrected program is below it.

a)

4 %: 4 <= 5, 4 <= 20 and 4 <= 50 are all True: 3 lines.

15 %: 15 <= 5 is False, the two others are True: 2 lines.

35 %: only 35 <= 50 is True: 1 line.

80 %: no condition is True: 0 lines.

b)

The if statements run in the order of the program: Shutting down soon comes first, then the two other messages below it.

The three conditions overlap: a level of 5 % or less is also 20 % or less and 50 % or less. Separate if statements therefore print every warning that applies, not the most urgent one.

c)

With elif, the chain stops at the first True condition: 4 % prints Shutting down soon only, and 15 % prints Low battery: saver mode on only.

1 line for each level, the most urgent warning, as the specification asks.

d)

4 <= 50 is True on the first test, so the program prints Consider charging and skips the rest.

When the conditions overlap, the cascade tests the most restrictive one first: 5, then 20, then 50.

Pitfall: a correct cascade in the wrong order. The order of the tests carries the logic.

e)

More than one line means at least two conditions True, that is battery <= 20, since battery <= 50 is then True as well.

The levels 0, 1, ..., 20 make 21 levels; 0 counts too.

Python
battery = int(input('Battery level (%): '))
if battery <= 5:
    print('Shutting down soon')
elif battery <= 20:
    print('Low battery: saver mode on')
elif battery <= 50:
    print('Consider charging')
LevelSeparate ifWith elifMessage with elif4 %31Shutting down soon15 %21Low battery: saver mode on35 %11Consider charging80 %00no messageLines printed: separate if against elif

Part B: problems and reasoning (/50)

Exercise 6: Problem: a climbing wall rule, from nested if statements to one condition

7 answers to check

A recreation centre lets a person climb its wall when two things hold: the person has a signed waiver, and the person is 12 or older, or else an adult supervisor is on site. The program below applies the rule. The variables age (an int), waiver and adult (two bool values) already hold the climber's data.

Python
if waiver:                          # line 1
    if age >= 12:                   # line 2
        print('You may climb')      # line 3
    elif adult:                     # line 4
        print('You may climb')      # line 5
    else:                           # line 6
        print('Not today')          # line 7
else:                               # line 8
    print('Not today')              # line 9
  • a) What does the program print for a climber of 10 who has a waiver, with no adult on site? For a climber of 10 who has a waiver, with an adult on site?
  • b) The program is rewritten as if ...: print('You may climb') else: print('Not today'). Which single condition gives the same decision as the nested if statements, for every input?
  • c) A student submits the condition waiver and age >= 12 or adult. What does it print for a climber of 9 with no waiver and an adult on site? Does it follow the rule?
  • d) The front desk wants the refusal tested first: if ...: print('Not today') else: print('You may climb'). Which condition is the exact opposite of the rule?
  • e) The three conditions age >= 12, waiver and adult can each be True or False, which makes 8 cases. In how many of them may the person climb?

Type your answers, the page tells you right or wrong 0/7

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Not today; You may climb
  • b) waiver and (age >= 12 or adult)
  • c) You may climb; no: Python reads (waiver and age >= 12) or adult
  • d) (not waiver) or (age < 12 and not adult)
  • e) 3 cases

Nested if statements are a hidden and: the inner test runs only when the outer test is True. Written as one condition, the rule reads in one line, provided the brackets follow the rule and not the order of the words. The truth table of the 8 cases is below.

a)

Age 10, waiver, no adult: line 1 is True, line 2 is False (10 >= 12 is False), line 4 is False: Not today.

Age 10, waiver, adult: line 1 is True, line 2 is False, line 4 is True: You may climb.

b)

The outer test is waiver. Inside it, line 2 and line 4 lead to the same message, so the inner part is age >= 12 or adult.

Joined: waiver and (age >= 12 or adult). The brackets are needed, since and has a higher rank than or.

c)

Python groups and before or: (waiver and age >= 12) or adult. For 9, no waiver and an adult on site: False or True is True, so the program prints You may climb, for a climber with no waiver.

The rule is broken: an adult on site lets anyone climb.

Pitfall: copying the words of the rule into a condition without brackets.

d)

Negate the rule with De Morgan's laws, one level at a time:

not (waiver and (age >= 12 or adult)) = (not waiver) or not (age >= 12 or adult)

= (not waiver) or (not age >= 12 and not adult)

= (not waiver) or (age < 12 and not adult).

The opposite of age >= 12 is age < 12: with age <= 12, a climber of 12 with a waiver and no adult would be refused, although the rule lets that climber in.

Pitfall: negating each part without exchanging and and or, which gives (not waiver) and (age < 12 or not adult). That condition is False for a climber of 15 with no waiver and an adult on site, so this climber would be let in without a waiver.

e)

The rule needs waiver True: 4 of the 8 cases. Among them, age >= 12 or adult is False only when both are False.

4 - 1 = 3 cases allow climbing.

age >= 12waiveradultMay climb?TrueTrueTrueYesTrueTrueFalseYesTrueFalseTrueNoTrueFalseFalseNoFalseTrueTrueYesFalseTrueFalseNoFalseFalseTrueNoFalseFalseFalseNoThe rule on its 8 cases: 3 of them allow climbing

Exercise 7: Problem: an unreachable branch in a UV index app

9 answers to check

A weather app turns the UV index forecast into a category of the UV index scale: Low below 3; Moderate from 3 to under 6; High from 6 to under 8; Very high from 8 to under 11; Extreme from 11 up. The figure draws these bands. The forecast is a number such as 4 or 7.5.

LowModerateHighVery highExtreme036811The UV index scale
Python
uv = float(input('UV index: '))     # line 1
if uv < 3:                          # line 2
    level = 'Low'                   # line 3
elif uv < 8:                        # line 4
    level = 'High'                  # line 5
elif uv < 6:                        # line 6
    level = 'Moderate'              # line 7
elif uv < 11:                       # line 8
    level = 'Very high'             # line 9
else:                               # line 10
    level = 'Extreme'               # line 11
print(level)                        # line 12
  • a) What does the app display for a forecast of 4.5? For 7?
  • b) Give, as an interval, the set of forecasts for which the program as written displays High.
  • c) For which forecasts does line 7, level = 'Moderate', run?
  • d) Which change makes the program follow the scale? After that change, give the interval of forecasts displayed Moderate.
  • e) After the change, what is displayed for 11? For 2.9? Give the interval of forecasts displayed Very high.

Type your answers, the page tells you right or wrong 0/9

a)
b)
Forecasts displayed High, as written ,
c)
d)
Forecasts displayed Moderate ,
e)
Forecasts displayed Very high ,
Show the solution

Answers

  • a) High for 4.5, which should be Moderate; High for 7
  • b) {u ∈ ℝ | 3 ≤ u < 8}, the interval [3, 8)
  • c) For no forecast: the branch is unreachable
  • d) Exchange the tests uv < 8 and uv < 6, each with its branch; Moderate on [3, 6)
  • e) Extreme; Low; Very high on [8, 11)

In a cascade of tests with <, a branch receives the values that are below its own bound and not below any bound tested above it. So the bounds are tested in increasing order. The figure compares the program as written with the corrected program, which is below.

a)

4.5: 4.5 < 3 is False, 4.5 < 8 is True, so High, while the scale says Moderate.

7: 7 < 3 is False, 7 < 8 is True, so High, which is right.

b)

Line 5 runs when line 2 is False and line 4 is True: uv >= 3 and uv < 8, so {u ∈ ℝ | 3 ≤ u < 8}, the interval [3, 8). The High branch takes the Moderate band as well.

c)

Line 6 is reached only when uv < 3 and uv < 8 are both False, that is when uv >= 8, and then uv < 6 is False. Line 7 runs for no forecast: it is unreachable code, and Python gives no warning.

Pitfall: checking each condition on its own. uv < 6 is the right test for Moderate, but in this place every value below 6 has already been taken by uv < 8.

d)

Exchange lines 4 and 5 with lines 6 and 7: the tests then read uv < 3, uv < 6, uv < 8, uv < 11, in increasing order.

Moderate is displayed when uv >= 3 and uv < 6: the interval [3, 6).

e)

11: the tests uv < 3, uv < 6, uv < 8 and uv < 11 are all False, since 11 < 11 is False, and the else displays Extreme, as the scale says from 11 up.

2.9 < 3 is True: Low.

Very high: uv >= 8 and uv < 11, the interval [8, 11).

Python
uv = float(input('UV index: '))
if uv < 3:
    level = 'Low'
elif uv < 6:
    level = 'Moderate'
elif uv < 8:
    level = 'High'
elif uv < 11:
    level = 'Very high'
else:
    level = 'Extreme'
print(level)
LowHighVery highExtreme03811As written: Moderate is never displayedLowModerateHighVery highExtreme038116Corrected: tests uv < 3, uv < 6, uv < 8, uv < 11

Exercise 8: Five statements to correct

11 answers to check

Each statement below was written on a unit test. Say whether it is true or false; if it is false, correct it. In every case, give the value asked, which supports your answer.

  • a) « In a chain if, elif, else, Python runs every branch whose condition is True. » The chain if n > 0: print('positive'), elif n > 10: print('large'), else: print('not positive') runs with n = 50. How many lines does it print?
  • b) « For any number x, exactly one of the two conditions x > 5 and x <= 5 is True. » For x = 5, how many of the two conditions are True?
  • c) « not (t > 0 and t < 10) can be written t <= 0 and t >= 10. » For t = 12, give the value of not (t > 0 and t < 10), then the value of t <= 0 and t >= 10.
  • d) « The block of if code == 7 or 9: runs only when code is 7 or 9. » Does the block run for code = 4?
  • e) « The opposite of temp >= 25 is temp <= 25. » For temp = 25, give the value of temp <= 25.

Type your answers, the page tells you right or wrong 0/11

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) False: only the first True branch runs; 1 line
  • b) True: 1 condition
  • c) False: it is t <= 0 or t >= 10; True, then False
  • d) False: the block runs for every code; yes
  • e) False: the opposite is temp < 25; True
a)

False. A cascade runs only the first branch whose condition is True. For n = 50, n > 0 is True: positive is printed, and n > 10 is not tested. 1 line.

In this order the branch large is unreachable, since every n > 10 is also > 0.

Correct statement: « In a chain if, elif, else, Python runs only the first branch whose condition is True. »

b)

True. x <= 5 is the opposite of x > 5: for every number, one of them is True and the other is False.

For x = 5: 5 > 5 is False and 5 <= 5 is True, so 1 condition is True.

c)

False. De Morgan's law turns the and into an or: not (t > 0 and t < 10) is t <= 0 or t >= 10.

For t = 12: t > 0 and t < 10 is True and False = False, so its negation is True.

t <= 0 and t >= 10 is False and True = False. No number is at most 0 and at least 10 at the same time, so the student's version is never True.

Correct statement: « not (t > 0 and t < 10) can be written t <= 0 or t >= 10. »

d)

False. Python reads (code == 7) or 9, and 9 counts as true: the block runs for every code, 4 included. Yes.

Correct statement: « The block of if code == 7 or code == 9: runs only when code is 7 or 9. »

e)

False. For temp = 25, temp >= 25 and temp <= 25 are both True, so they are not opposites. The opposite of >= is <.

Correct statement: « The opposite of temp >= 25 is temp < 25. »

Exercise 9: Problem: a greenhouse controller and its test plan

10 answers to check

A school greenhouse opens its roof vents when the temperature reaches 28 °C or more, or when the relative humidity is above 85 %. A student wrote the program below. The teacher's test plan, in the table, gives eight test cases; the expected result of each one is for you to work out.

TestTemperature (°C)Humidity (%)
13060
22860
32590
42585
53190
62050
72886
827.985
Python
temp = float(input('Temperature (°C): '))     # line 1
humidity = float(input('Humidity (%): '))     # line 2
if temp > 28 and humidity > 85:               # line 3
    print('Vents open')                       # line 4
else:                                         # line 5
    print('Vents closed')                     # line 6
  • a) Work out the expected result of each test from the specification. What is expected for test 2? For test 4? For test 8?
  • b) Run line 3 as written on the eight tests. How many tests fail?
  • c) The student replaces and by or and keeps temp > 28. How many tests fail now, and which one?
  • d) Which line 3 passes the eight tests? The student's first test plan had only tests 5 and 6. How many of them fail with the original line 3?
  • e) The controller must also turn on a heater below 12 °C, whatever the vents do. A student adds the heater test as an elif placed right after the vent test of the corrected program: if temp >= 28 or humidity > 85: print('Vents open'), then elif temp < 12: print('Heater on'), then else: print('Vents closed'). For 10 °C and 90 %, is the heater turned on? Should the heater test be an elif or a separate if?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Test 2: open; test 4: closed; test 8: closed
  • b) 4 tests fail: 1, 2, 3 and 7
  • c) 1 test fails: test 2
  • d) if temp >= 28 or humidity > 85:; 0 of the two fail
  • e) No; a separate if

A test fails when the actual result differs from the expected result. Work out the expected column from the specification first, without looking at the code, then run the code on each row. The completed plan is below, and the corrected program, heater included, below it.

a)

The vents open when temp >= 28 or humidity > 85.

Test 2, 28 °C and 60 %: 28 >= 28 is True, so Vents open.

Test 4, 25 °C and 85 %: 25 >= 28 is False and 85 > 85 is False, so Vents closed: 85 % is not above 85 %.

Test 8, 27.9 °C and 85 %: both sides are False, so Vents closed.

b)

Line 3 needs both temp > 28 and humidity > 85. It opens the vents for test 5 only (31 °C and 90 %), and the plan expects open for tests 1, 2, 3, 5 and 7.

Tests 1, 2, 3 and 7 fail: 4 tests. Tests 4, 5, 6 and 8 pass.

c)

With temp > 28 or humidity > 85, test 1 (30 > 28), test 3 (90 > 85) and test 7 (86 > 85) now open, as expected.

Test 2 still fails: 28 > 28 is False and 60 > 85 is False, so the vents stay closed at 28 °C. 1 test fails, the boundary test 2.

d)

if temp >= 28 or humidity > 85: passes the eight tests.

Tests 5 and 6 both pass with the original line: 31 °C and 90 % make both sides True, 20 °C and 50 % make both sides False, and and gives the same result as or when its two sides are equal. 0 of them fail, and the two bugs stay hidden.

Pitfall: a test plan without a case where only one condition is True, and without the boundary values 28 °C and 85 %.

e)

For 10 °C and 90 %, the vent test is True, so its branch runs and the elif is skipped: the heater stays off. No.

The heater decision does not depend on the vents: it needs its own if statement, if temp < 12: print('Heater on'). Separate if statements suit independent decisions; a cascade suits cases of which a single one must run.

Python
temp = float(input('Temperature (°C): '))
humidity = float(input('Humidity (%): '))
if temp >= 28 or humidity > 85:
    print('Vents open')
else:
    print('Vents closed')
if temp < 12:
    print('Heater on')
Test°C%ExpectedActualResult13060openclosedfail22860openclosedfail32590openclosedfail42585closedclosedpass53190openopenpass62050closedclosedpass72886openclosedfail827.985closedclosedpassTest plan run on line 3 as written

Exercise 10: Problem: time-of-use electricity prices, from the specification to the program

10 answers to check

An electricity utility charges by time of use. Its winter schedule, with the prices of this exercise: on weekdays, on-peak from 7 h to 11 h and from 17 h to 19 h, 15.8 cents per kWh; mid-peak from 11 h to 17 h, 12.2 cents per kWh; off-peak from 19 h to 7 h, 7.6 cents per kWh. Saturdays and Sundays are off-peak all day. The figure draws a weekday.

An hour h is the hour that starts at h, a whole number from 0 to 23: « from 7 h to 11 h » covers the hours 7, 8, 9 and 10. Write a program that reads the day, 1 for Monday up to 7 for Sunday, then the hour, and displays the period and its price. The three prices are constants of the program.

7.615.812.215.87.60711171924A weekday in winter, hours 0 to 24, prices in cents per kWhoff-peakon-peakmid-peakon-peakoff-peak
  • a) Write the program. What does it display for Tuesday (day 2) at 8 h: which period, and which price?
  • b) Which period does it display for Thursday at 19 h? For Saturday at 8 h?
  • c) A dryer cycle uses 3 kWh within one hour. What does it cost, in cents, on a Wednesday at 18 h? At 20 h? How many cents does waiting save?
  • d) How many of the 24 hours of a weekday are on-peak? How many of the 168 hours of a week are off-peak?
  • e) A classmate's program tests if hour >= 7 and hour < 11 or hour >= 17 and hour < 19: for on-peak, then elif hour >= 11 and hour < 17: for mid-peak, else off-peak, and never reads the day. For how many of the 168 hours of a week does it display a wrong period?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) on-peak, 15.8 cents per kWh
  • b) off-peak; off-peak
  • c) 47.4 cents; 22.8 cents; 24.6 cents saved
  • d) 6 hours; 108 hours
  • e) 24 hours, all of them on the weekend

The IPO chart first. Input: the day and the hour, two int. Processing: one cascade that chooses the period. Output: the period and its price. Off-peak is tested first: on the weekend every hour is off-peak, so the day belongs in its condition, joined by or with the two night ranges. On-peak, last, gets what remains. The program is below.

a)

Day 2, hour 8: day >= 6 is False, 8 < 7 is False and 8 >= 19 is False, so the first test is False. 8 >= 11 is False, so the elif is False.

The else gives on-peak, and the program displays on-peak 15.8 cents per kWh.

b)

Thursday, 19 h: 19 >= 19 is True, so off-peak. « From 17 h to 19 h » stops before the hour 19, so 19 belongs to the evening off-peak period.

Saturday, 8 h: day >= 6 is True, so off-peak, whatever the hour.

Pitfall: writing hour > 19, which puts the hour 19 in on-peak.

c)

At 18 h on a Wednesday, on-peak: 3 × 15.8 = 47.4 cents.

At 20 h, off-peak: 3 × 7.6 = 22.8 cents.

Saved: 47.4 - 22.8 = 24.6 cents, about half the cost.

d)

On-peak hours of a weekday: 7, 8, 9, 10, then 17, 18, that is 4 + 2 = 6 hours.

Off-peak on a weekday: the hours 0 to 6 (7 hours) and 19 to 23 (5 hours), 12 hours. A week has 5 weekdays and 2 weekend days: 5 × 12 + 2 × 24 = 60 + 48 = 108 hours.

e)

The first condition is right as written: and runs before or, so it reads (hour >= 7 and hour < 11) or (hour >= 17 and hour < 19).

The bug is the missing day. On Saturday and on Sunday, the program displays on-peak for 6 hours and mid-peak for 6 hours, where the schedule says off-peak: 2 × (6 + 6) = 24 wrong hours out of 168. The 120 weekday hours are right.

Python
ON_PEAK = 15.8    # cents per kWh
MID_PEAK = 12.2
OFF_PEAK = 7.6
day = int(input('Day (1 = Monday ... 7 = Sunday): '))
hour = int(input('Hour (0 to 23): '))
if day >= 6 or hour < 7 or hour >= 19:
    period = 'off-peak'
    price = OFF_PEAK
elif hour >= 11 and hour < 17:
    period = 'mid-peak'
    price = MID_PEAK
else:
    period = 'on-peak'
    price = ON_PEAK
print(period, price, 'cents per kWh')
Something missing from this set? A type of exercise your teacher gives, a problem you are stuck on, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Exercise set published at www.letuteurscientifique.ca/en/exercices/ics3u-selection-boolean-logic. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session: conditions, boundaries and test plans come back in every later unit of the course.

Site by Studio Squalli