ICS3U Computer Science • Ontario Grade 11

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

This sheet is not a summary of the selection chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks on conditions, if, elif and else, and which precise gesture avoids each loss.

The mistakes of this chapter are silent: a cascade in the wrong order, a < in place of <=, a condition that is always true, all run to the end without any error message and give a wrong answer for some inputs only. The code is in Python 3, and every value on this sheet comes from a program that was run.

  • 8 mistakes that cost marks
  • 4 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

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.

Topics covered

  • Boolean expression
  • Comparison operators
  • Boolean operators and, or, not
  • Truth table
  • De Morgan's laws
  • Selection structure
  • If, elif and else cascade
  • Nested if statements
  • Operator precedence in conditions
  • Boundary value
  • Unreachable branch
  • Test case

The essentials

A condition is a value: True or False

  • • A comparison gives a bool: == (equal to), != (not equal to), <, >, <= (less than or equal to), >= (greater than or equal to). A single = is an assignment, and Python refuses it in a condition.
  • • and is True only 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. x + 1 > 5 or y == 0 and z < 3 is read (x + 1 > 5) or ((y == 0) and (z < 3)).
  • • Each side of and or or is a complete condition: x == 1 or x == 2, never x == 1 or 2.
  • • The opposite of < is >=, and the opposite of <= is >: the boundary value changes sides.

In doubt, add brackets: they cost nothing and show the reader which operator runs first.

A cascade runs one branch, separate if statements can run several

  • • if, elif, else: Python tests from the top, runs the first branch whose condition is True, then jumps past the end of the chain. The else runs only when every test above it was False.
  • • Each elif is therefore read knowing that every test above it was False: elif t > 30 placed after if t > 35 means 30 < t ≤ 35.
  • • Separate if statements are tested one after the other, each on its own: every one whose condition is True runs.
  • • A nested if runs only when the outer test is True: if a: then if b: inside it is the same decision as if a and b:.
  • • A branch whose condition can never be True when Python reaches it is unreachable, and Python gives no warning.
if / elif / else: one branch runst > 35?t > 30?Heat alertHotyesyesnonoNormalnext lineTwo separate if: both can runt > 35?t > 30?Heat alertHotyesyesnononext line
For t = 37, the cascade on the left prints Heat alert only; the two separate if statements on the right print Heat alert, then Hot.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

The opposite of a condition

The opposite is True exactly where the condition is False. Every example was run in Python 3.

ConditionTrue forIts opposite
x < 5 numbers below 5 x >= 5

Example: For x = 5: x < 5 is False and x >= 5 is True; the value 5 changes sides.

x <= 5 5 and the numbers below x > 5

Example: For x = 5: x <= 5 is True and x > 5 is False.

x == 5 5 only x != 5

Example: For x = 4: x == 5 is False and x != 5 is True.

a and b both True (not a) or (not b)

Example: With a meaning x > 0 and b meaning x < 5, for x = 7: a and b is True and False = False, and (not a) or (not b) is False or True = True.

a or b at least one True (not a) and (not b)

Example: With a meaning x < 0 and b meaning x > 10, for x = 4: a or b is False or False = False, and (not a) and (not b) is True and True = True.

0 < t and t < 10 t from 1 to 9, for whole t t <= 0 or t >= 10

Example: For t = 12: 0 < t and t < 10 is False, and t <= 0 or t >= 10 is True.

a and b both True (not a) and (not b) wrong opposite

Example: With a meaning x > 0 and b meaning x < 5, for x = 7: not (a and b) is True, but (not a) and (not b) is False and True = False.

What to do: Negate each part and exchange the operator: the opposite of a and b is (not a) or (not b).

Check an opposite on the boundary value: a condition and its opposite are never True together, and one of them is always True.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. A cascade whose broad test comes first

1 to 2 marks, and a branch that never runs

What not to write

“if temp > 30: print('Hot'), then elif temp > 35: print('Heat alert'): at 37 °C the program prints Heat alert.”

What to write

“temp > 30 is True at 37, so the program prints Hot and stops. Test the narrow condition first: if temp > 35, then elif temp > 30.”

Why: Every temperature above 35 is also above 30. Placed second, temp > 35 is tested only when temp <= 30, where it is always False.

2. « From 100 dollars » coded with >

1 mark, and a program wrong for one value only, the one a test plan must try

What not to write

“10 % off from 100 dollars: if total > 100: discount = 0.10.”

What to write

“« From 100 dollars » includes 100: if total >= 100:. For a total of 100 dollars, the discount is 10 dollars.”

no discount10 % off100: no discountif total > 100: 100 dollars gets no discountno discount10 % off100: 10 % offif total >= 100: 100 dollars gets the discount
The two programs agree on every total except 100: with >, a total of exactly 100 dollars falls in the band without a discount.

Why: > and >= differ on the boundary value only: 100 > 100 is False, while 100 >= 100 is True.

3. Comparing one variable with two values

the whole question: every input takes the same branch

What not to write

“if day == 6 or 7: print('Weekend') prints Weekend on Saturday and Sunday only.”

What to write

“if day == 6 or day == 7:. Python reads the first version as (day == 6) or 7, and 7 counts as true: Weekend is printed every day.”

Why: Each side of or is a condition of its own, and a number other than 0 counts as true in a condition. Java refuses day == 6 || 7 at compile time.

4. Negating a condition with and

1 to 2 marks on a truth table, and the wrong branch on two rows out of four

What not to write

“not (raining and cold) is the same as not raining and not cold.”

What to write

“not (raining and cold) is (not raining) or (not cold): it is True as soon as one of the two is False.”

rainingcoldnot (raining and cold)not raining and not coldTrueTrueFalseFalseTrueFalseTrueFalseFalseTrueTrueFalseFalseFalseTrueTrueNot the same column: two rows out of four differ
On the two middle rows, where exactly one of raining and cold is True, not (raining and cold) is True and not raining and not cold is False.

Why: De Morgan's laws: the negation of an and is an or of the negations, and the negation of an or is an and of the negations.

5. Separate if statements where one message is expected

1 mark per extra line in a predicted output

What not to write

“if points >= 90: print('Gold'), then if points >= 75: print('Silver'): 95 points earn Gold.”

What to write

“The two if are independent: 95 points print Gold, then Silver. Write elif points >= 75: for a single medal.”

Why: Each separate if is tested; an elif is tested only when every test above it was False.

6. Writing the opposite of a comparison

1 mark, and the value 50 handled twice or not at all

What not to write

“The opposite of speed <= 50 is speed >= 50.”

What to write

“The opposite of speed <= 50 is speed > 50. At 50, speed <= 50 and speed >= 50 are both True.”

Why: A condition and its opposite split the numbers in two: the boundary value goes to one side only.

7. Mixing and with or without brackets

1 to 2 marks: the program runs, and is wrong for some inputs

What not to write

“if vip or points > 500 and active: gives the reward to active accounts only.”

What to write

“Python reads vip or (points > 500 and active): an inactive vip gets the reward. Write (vip or points > 500) and active.”

Why: and has a higher rank than or, as × has a higher rank than +.

8. Writing = in a condition

the whole program, which does not start

What not to write

“if level = 3: print('Boss')”

What to write

“if level == 3: print('Boss'). Python refuses the first line before running anything, with a SyntaxError.”

Why: = stores a value in a variable; == compares two values and gives True or False.

Which method to choose

if, elif or a separate if?

Ask how many branches may run for one input.

  • If the cases exclude each other and one outcome is expected: a category, a price, a single message → one cascade if, elif, else, with the narrow test first, or the bounds in increasing order with <

    Example: if t < 0: 'ice', elif t < 100: 'water', else: 'steam'

  • If the decisions are independent: each one may happen or not → one separate if per decision

    Example: if late: add a fee, then a separate if member: apply the discount

  • If a test only matters when another one holds → a nested if, or one condition joined by and

    Example: if logged_in: then if admin: inside it is if logged_in and admin:

  • If one variable compared with several values → one complete comparison per value, joined by or

    Example: day == 6 or day == 7, or the chained comparison 6 <= day <= 7

A cascade with no else displays nothing for the inputs no test catches: decide whether that is what the specification wants.

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Tracing a selection on a unit test

When to use it: « What does this program display for ...? » on a chain of if, elif, else, or on separate if statements

  1. 1 Replace every variable by its value, then compute in order: arithmetic, comparisons, not, and, or.
  2. 2 Write each test with its line number and its value: « line 5: percent < 60 is False ».
  3. 3 In a cascade, stop at the first True test: its branch runs, and the tests below it are not evaluated.
  4. 4 With separate if statements, test every one of them: each True condition prints its message.
  5. 5 Copy the exact characters displayed, one line per print, in the order they run.

Concluding sentence

“Line 5: 73.89 < 60 is False; line 7: 73.89 < 70 is False; line 9: 73.89 < 85 is True, so zone = 3 and the else is skipped.”

The trap: Evaluating the tests below the first True one, and printing two messages for a cascade.

Marking: A common split: 1 mark per test evaluated, 1 for the output.

Writing a selection from a specification

When to use it: « Write a program that displays the category, the price or the message for ... »

  1. 1 Write each band as an interval with its two ends: « from 60 % to under 70 % » is [60, 70).
  2. 2 Decide each comparison from the words: « from », « at least », « up to and including » include the boundary; « under », « below », « above » exclude it.
  3. 3 Order the tests: with <, the bounds in increasing order; the last band goes in the else.
  4. 4 Write each condition with complete comparisons and brackets where and meets or.
  5. 5 Trace the program on each boundary: just below it, on it, just above it.

Concluding sentence

“Zone 3 covers [70, 85): for a maximum of 203, 142 beats per minute give 69.95 %, Zone 2, and 143 give 70.44 %, Zone 3.”

The trap: Testing only typical values, in the middle of each band, which never reveal a < written in place of <=.

Marking: A common split: 1 mark for the order of the tests, 1 for the boundaries, 1 for the trace.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • Every boundary traced

    For each number written in the specification, trace the program on that number itself.

    A rule « from 100 dollars » traced at 100 shows at once whether > or >= was written.

  • Every branch reachable

    For each branch, find one input that reaches it.

    No temperature reaches elif temp > 35 placed after if temp > 30: a broader test above it takes all its values.

  • An opposite checked on its boundary

    A condition and its opposite give different values on the boundary.

    speed <= 50 and speed >= 50 are both True at 50: one of them is not the opposite of the other.

  • One message per input in a cascade

    Count the lines printed for one input: a chain if, elif, else prints the message of one branch at most.

    Gold and Silver both printed for 95 points mean two separate if statements, not a cascade.

The typical problem, taken apart

Heart-rate zones of a fitness watch

A fitness watch estimates the maximum heart rate as 220 minus the age, a rough rule of thumb, then shows a training zone from the heart rate measured: below 60 % of the maximum, Zone 1; from 60 % to under 70 %, Zone 2; from 70 % to under 85 %, Zone 3; 85 % and over, Zone 4.

Write the selection, then trace it for a 17-year-old whose heart rate is 150 beats per minute. Which whole heart rates give Zone 3 at this age?

Python
age = int(input('Age: '))
bpm = int(input('Heart rate (beats/min): '))
maximum = 220 - age
percent = bpm / maximum * 100
if percent < 60:
    zone = 1
elif percent < 70:
    zone = 2
elif percent < 85:
    zone = 3
else:
    zone = 4
print('Zone', zone)

Step 1

The bands as intervals: Zone 1 below 60, Zone 2 on [60, 70), Zone 3 on [70, 85), Zone 4 from 85 up, in percent of the maximum. Each lower end is included, each upper end excluded.

Why

Writing the ends before the code decides every < and <=: « from 60 % » includes 60, « under 70 % » excludes 70.

Step 2

The tests, with < in increasing order: percent < 60, then percent < 70, then percent < 85, then the else.

Why

Each elif is reached only when the tests above it were False, so percent < 70 there means 60 ≤ percent < 70: the lower ends need no test of their own.

Step 3

Trace for 17 and 150: maximum = 220 - 17 = 203 and percent = 150 / 203 × 100 = 73.89...; 73.89 < 60 is False, 73.89 < 70 is False, 73.89 < 85 is True, so Zone 3.

LineAssignment or outputTestValue1age = 172bpm = 1503maximum = 2034percent = 73.89...5percent < 60False7percent < 70False9percent < 85True10zone = 313output: Zone 3Trace for age 17 and 150 beats per minute

Why

The trace stops at the first True test: the else is not reached, and one line is printed.

Step 4

Zone 3 at this age: 70 % of 203 is 142.1 and 85 % of 203 is 172.55, so the whole heart rates from 143 to 172 beats per minute.

Why

A boundary is checked by the values around it: 142 gives 69.95 %, Zone 2; 143 gives 70.44 %, Zone 3; 172 gives 84.73 %, Zone 3; 173 gives 85.22 %, Zone 4.

The conclusion, written out

“For a 17-year-old at 150 beats per minute, percent = 73.89, so the watch shows Zone 3; at this age Zone 3 covers 143 to 172 beats per minute.”

The classic mistake on this problem: Testing the bounds in decreasing order with <: if percent < 85 comes first, every heart rate below 85 % gives Zone 3, and Zones 1 and 2 are never shown.

Learn by heart

  • • == compares, = assigns; != means not equal to.
  • • Order in a condition: arithmetic, comparisons, not, and, or.
  • • In a cascade, only the first True branch runs: narrow test first, or the bounds in increasing order with <.
  • • Separate if statements all run when their condition is True: one if per independent decision.
  • • x == 1 or x == 2, never x == 1 or 2.
  • • not (a and b) is (not a) or (not b); not (a or b) is (not a) and (not b).
  • • The opposite of < is >=, and the opposite of <= is >.
  • • Test each boundary: just below it, on it, just above it.

Frequently asked questions

What is the difference between if, elif and else in Python?

An if tests its condition and runs its block when the condition is true. An elif is tested only when every test above it in the same chain was false, and an else runs when all of them were false. So in one chain of if, elif and else, at most one block runs, the first whose condition is true. Two separate if statements, on the other hand, are each tested, and both can run.

Why is my condition x == 1 or 2 always true in Python?

Because Python compares first and then applies or to what is on each side: it reads the comparison of x with 1, or the number 2 alone. In a condition, any number other than zero counts as true, so the right side is always true and the block always runs. Write a full comparison on each side: x equal to 1, or x equal to 2. In Java the same line does not compile.

What are De Morgan's laws in programming?

They say how to negate a condition made of two parts. The opposite of a and b is not a, or not b: it is enough that one part is false. The opposite of a or b is not a, and not b: both parts must be false. Negating each part is not enough: the and must become an or, and the or an and. A truth table of four rows checks it.

Should I use less than or less than or equal to in an if statement?

Read the rule for the boundary value. Words such as up to and including, at most, at least or from mean the boundary is included: less than or equal to, or greater than or equal to. Words such as under, below or above mean it is excluded: strictly less than, or strictly greater than. Then test the program on the boundary itself, just below it and just above it.

Why does my Python program print several messages instead of one?

Because it uses separate if statements, and each one whose condition is true runs its block. When the cases overlap, such as a level of at most 5 that is also at most 20, several messages appear. To show one message, write a single chain of if, elif and else, with the most restrictive condition first: Python then stops at the first true condition.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: Selection: if, elif, else and Boolean logic, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 11 corrected exercises
  • 110 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, 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. Revision sheet published at www.letuteurscientifique.ca/en/fiches/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.

Site by Studio Squalli