Grade by Grade
A. Programming Concepts and Skills · Programming Basics: Data, Decisions and Loops

Boolean Expressions: Comparison and Logical Operators

A1.4 A1.1About 65 minutes
Learning goals
  • I can use the six comparison operators to make Boolean expressions.
  • I can combine conditions with and, or and not, and complete truth tables.
  • I can evaluate compound Boolean expressions using the order of operations.
  • I can write a Boolean expression for a rule given in words.
  • I can store the result of a condition in a Boolean variable.

Words to know

Boolean expression (condition)
An expression whose value is True or False, such as age >= 16.
comparison operator
One of ==, !=, <, >, <=, >=. It compares two values and gives a Boolean.
logical (Boolean) operator
and, or or not. Combines or reverses Boolean values.
compound condition
A condition built from smaller conditions joined by and or or.
truth table
A table that lists every combination of True and False inputs and the result of an expression for each.
short-circuit evaluation
Python stops evaluating and/or as soon as the answer is known: False and ... is False, and True or ... is True, without looking at the rest.

Yes-or-no questions

Is it below −25 °C? Is the user 16 or older? Did the player type the right password? Programs make decisions by asking questions whose answer is True or False. Those questions are Boolean expressions. You met the bool type in Lesson 3; now you will build Boolean values with operators. In the next lesson, you will use them to make your programs choose what to do.

OperatorMeaningExample (x = 7)Result
==equal tox == 7True
!=not equal tox != 7False
>greater thanx > 10False
<less thanx < 10True
>=greater than or equal tox >= 7True
<=less than or equal tox <= 6False
The six comparison operators listed in expectation A1.4.

`=` is not `==`

One equal sign assigns (x = 7 gives x the value 7). Two equal signs compare (x == 7 asks "is x equal to 7?"). Writing if x = 7: is a syntax error in Python.

Comparing other types

  • Numbers: ints and floats compare normally: 3 == 3.0 is True. Avoid == with float results of calculations: 0.1 + 0.2 == 0.3 is False (Lesson 5). Compare rounded values instead.
  • Strings are compared character by character using their codes (Lesson 6). "apple" < "banana" is True, "Apple" == "apple" is False, and every capital comes before every lower-case letter.
  • Python's chained comparisons: 13 <= age <= 19 means 13 <= age and age <= 19. Many other languages do not allow this, but Python does.
10111213141516171819202122
The values of age that make 13 <= age <= 19 True (whole numbers). Both ends are included because the operators are <=.

Logical operators: and, or, not

  • A and B is True only when both A and B are True.
  • A or B is True when at least one of them is True (including both).
  • not A reverses A: not True is False.

For example, with temp = -28 and snow_cm = 5:

  • temp <= -25 and snow_cm >= 20 is True and False, which is False.
  • temp <= -25 or snow_cm >= 20 is True or False, which is True.
ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue
The truth table for the three logical operators. Two inputs give 2 × 2 = 4 rows.
A and BABA or BABshaded: both are Trueshaded: at least one is TrueCircle A: the cases where A is True. Circle B: the cases where B is True.
and is True only where both conditions are True (the overlap). or is True where at least one is True (anywhere in either circle).

Order of operations, completed

You now have three families of operators. Python evaluates them in this order:

  1. arithmetic (with its own order from Lesson 4),
  2. comparisons,
  3. not,
  4. and,
  5. or.

So x + 1 > 5 and not done means ((x + 1) > 5) and (not done). Because and comes before or, a or b and c means a or (b and c). Use parentheses whenever a reader might wonder; they cost nothing and prevent bugs.

age >= 13 and age <= 19 or has_passage = 21, has_pass = True(21 >= 13) and (21 <= 19) or Trueput in the valuesTrue and False or Truecomparisons done firstFalse or Trueand done nextTrueor done last
Evaluating a compound condition step by step: arithmetic, then comparisons, then not, then and, then or. Here the person is not a teen, but has a pass, so the result is True.

Boolean variables

You can store a condition's result in a variable, which makes later code easier to read. Name Boolean variables like yes/no questions: is_member, has_ticket, can_vote.

In Ontario you can apply for a G1 driver's licence at 16, so a program might use can_get_g1 = age >= 16.

age = 15
can_get_g1 = age >= 16
is_teen = 13 <= age <= 19
print(can_get_g1, is_teen)
print(not can_get_g1 and is_teen)
print("Zebra" < "apple", "cat" == "Cat")

Boolean variables hold the result of a comparison. In line 5, not is applied before and. Output, line by line: False True | True | True False

Worked example

Example 1: Evaluate the expression

With x = 4, y = 10 and done = False, evaluate x * 2 > y or not done and y % x == 2.

  1. Arithmetic first: x * 2 is 8, and y % x is 10 % 4 = 2.
  2. Comparisons: 8 > 10 is False; 2 == 2 is True. Now it reads False or not done and True.
  3. not done is not False, which is True. Now: False or True and True.
  4. and before or: True and True is True. Then False or True is True.

The expression is True.

Worked example

Example 2: From words to code

A ski club accepts a student who is in grades 9 to 12 and who either has a signed permission form or is at least 18. Write the condition using grade, has_form and age.

  1. Split the rule into parts: "grades 9 to 12" is 9 <= grade <= 12.
  2. "has a signed form or is at least 18" is has_form or age >= 18.
  3. Both parts must be true, so join them with and.
  4. Because and comes before or, the or part must be in parentheses. Without them, 9 <= grade <= 12 and has_form or age >= 18 would accept anyone aged 18 or older, whatever their grade, even with grade = 7.
  5. Test: grade 10, no form, age 16 → True and (False or False) → False. ✓

can_join = 9 <= grade <= 12 and (has_form or age >= 18)

Just for fun

Ask a programmer "Would you like tea or coffee?" and you might get the answer "Yes."

To a computer, tea or coffee is True if they want at least one of them.

Hands-on activity

Coin truth tables and house rules

You need: two coins, paper and a pencil, and Python.

  1. Let coin A and coin B stand for two conditions: heads = True, tails = False. Set the coins to each of the 4 combinations. For each one, write the values of A and B, A or B and not A. Compare your table with the one in this lesson.
  2. Write three household rules as Boolean expressions with clear variable names. Example: "You can have screen time if your homework is done and it is before 9 p.m., or if it is a holiday" becomes homework_done and hour < 21 or is_holiday.
  3. For each rule, test at least 3 cases with real family members ("Dad, homework not done, 8 p.m., not a holiday"). Write down the result you expect.
  4. Type each rule into Python with test values and check your predictions.

What to look for: the coin table matches the lesson's truth table. The rule in step 2 works without parentheses because and is done before or, but adding (homework_done and hour < 21) or is_holiday makes the meaning clearer, which is better style.

Your turn

1

With a = 5 and b = 8, evaluate a == b, a != b, a >= 5 and b < a.

2

Evaluate True and not False.

3

Evaluate 3 > 2 or 1 / 1 > 5.

4

Write a Boolean expression that is True when temp is below freezing (0 °C).

5

Write a condition that is True when score is from 0 to 100 inclusive, in two ways.

6

Write a condition that is True when n is even and not a multiple of 4.

7

Is "Toronto" < "ottawa" True or False? Why?

More practice: warm-up

1

What does != mean?

2

What is not True?

3

What is False or True?

4

What is True and False?

5

What is the value of 7 >= 7?

More practice: on your own

1

With x = 3, y = 6 and ok = True, evaluate x + y == 9 and not ok or y > 5.

2

A movie discount applies if age < 13 or age >= 65. Write the condition and test it with ages 12, 13, 40 and 65.

3

A student writes x == 1 or 2 to test whether x is 1 or 2. Why is this wrong? Fix it.

4

Complete a truth table for not (A or B) for all four combinations of A and B.

5

Write a condition for a valid Canadian postal-code length test: code has exactly 6 or 7 characters. (Use len(code) to get the number of characters.)

Challenge

1

Use truth tables to show that not (A and B) gives the same results as not A or not B (one of De Morgan's laws).

2

Rewrite not (temp >= 0 and temp <= 30) without using not.

3

Explain why y != 0 and x / y > 2 is safe when y is 0, but x / y > 2 and y != 0 crashes.

Check your understanding

Quiz

1.

What is the value of 10 != 10?

2.

When is A and B True?

3.

What is False or not False?

4.

Which condition tests whether n is between 1 and 10 inclusive?

5.

In a or b and c, which is evaluated first?

6.

What is "apple" == "Apple"?

7.

Which line compares instead of assigning?

For parents and teachers

Big idea: expectation A1.4 lists the Boolean operators (AND, OR, NOT), the six comparison operators and the order of operations. This lesson prepares for selection (Lessons 9 and 10) and loops (Lessons 11 to 13).

How to help: turn a family rule into a Boolean expression together and then test it with "what if" cases. Arguing about whether a rule needs parentheses is great practice.

Common difficulties:

  • Using = (assign) when == (compare) is needed.
  • Writing x == 1 or 2 instead of x == 1 or x == 2.
  • Mixing up and and or when translating words. "Between 1 and 10" needs and; "under 13 or 65 and over" needs or.
  • Forgetting that and is done before or, so missing parentheses.