Week 8 · Unit 7.2: Decomposing problems · 3 lessons
2
Greater, less or equal
Computing 7: Unit 7.2, pp. 44–81
GoalUse comparison operators and if … else in flowcharts and MicroPython, and predict results around the threshold.
New words
comparison operator · a symbol that compares two values, such as < or >=threshold · the value at which the answer of a question changeselse · the part of an if statement that runs when the answer is no== · two equals signs: asks “is it equal to?”; a single = stores a value instead
Explanation
A decision compares a sensor number with a threshold. There are six symbols: < (smaller than), > (bigger than), <= (smaller than or the same as), >= (bigger than or the same as), == (the same as) and != (different from). Be careful at the threshold itself: < and > do not include it, but <= and >= do. The yes path says what happens when the comparison is true. The no path is called else. In MicroPython the word else: lines up with the if above it. Changing one operator changes the program. In Python the single sign = stores a value, so to compare you must write ==.
Symbol
Meaning
Test with 20
<
smaller than
20 < 25 is true
>
bigger than
20 > 25 is false
<=
smaller than or the same as
20 <= 20 is true
>=
bigger than or the same as
20 >= 25 is false
==
the same as
20 == 20 is true
!=
different from
20 != 20 is false
Worked examples
A classroom reminder: if the temperature is 28 or more, show a cross to say “open a window”. Otherwise show a tick.
a cross at 28 degrees or hotter; a tick when cooler
This is the same plan in MicroPython. The else: is at the same indentation as the if.
Temperature
if temperature() >= 28
if temperature() > 28
27
no
no
28
yes
no
29
yes
yes
The operator matters most at the threshold. Compare >= with > when the temperature is exactly 28.
Class activity
Threshold game (no computer). Make eight number cards from 10 to 40, for example 12, 20, 25, 28, 30, 33, 35 and 40. Make a rule card such as “temperature > 28”. Sort the cards into a YES pile and a NO pile. Then change the rule card to “temperature >= 28” and sort again. Which card moved? Write down why. Try the same with “temperature == 30” and “temperature != 30”.
Practice
1
What does the board show when the light level is 59, 60 and 61?
At 59: Dark, because 59 < 60 is true. At 60: Bright, because 60 < 60 is false. At 61: Bright.
2
Choose the operator: (a) warn when the temperature is 35 or more; (b) do something only when the light level is exactly 100; (c) do something when the number is anything but 0.
(a) >= (b) == (c) !=
3
This line has a syntax error. Find it and write the correct line.