☰ Year plan · Communication Technology

Formulas, comparisons and loops

Week 3 · Unit 1, Lesson 1 Computational Thinking and Problem Solving (3) · 3 lessons
2

The larger of two numbers

ICT Prep 3 Term 1, Unit 1, Lesson 1: pp. 10–17
GoalUse a comparison and if/else to show the larger of two numbers, and handle equal numbers.
New words
comparison · a test between two values that gives true or false> · true when the left value is larger than the right one>= · true when the left value is larger than or equal to the right oneelse · the block that runs when the if condition is false
Explanation

Which of two numbers is larger? Decomposition: read a, read b, compare, show one of them. The comparison a > b is true when a is larger. Python has more signs: < for smaller, >= for larger or equal, <= for smaller or equal, == for equal. The program shows a if a > b is true, and b if it is false. What if the numbers are equal, for example 9 and 9? Then a > b is false, so the else branch runs and shows b. This is still right, because b is 9 and the larger number is 9. The code shows a good habit: think about the border case, here equal numbers, before you trust the program.

Startread a, ba > byesnoshow ashow bEnd
Worked examples
Python
1a = int(input("First number: "))
2b = int(input("Second number: "))
3if a > b:
4    print(a)
5else:
6    print(b)
Output
First number: 8
Second number: 15
15
The user types 8 and 15. The condition 8 > 15 is false, so the else branch shows 15.
Python
1a = int(input("First number: "))
2b = int(input("Second number: "))
3if a > b:
4    print(a)
5else:
6    print(b)
Output
First number: 9
Second number: 9
9
The user types 9 twice. The condition 9 > 9 is false, so the else branch runs and shows 9. The answer is right, because both numbers are the larger one.
Class activity

Change the program on paper so that it shows the smaller number. Which sign do you change? Test it with 12 and 5, and with 7 and 7. Then write a program idea that says Pass when a mark is at least 50.

Practice
1
What does the program of this lesson show for 20 and 7?
2
What does the program show for 5 and 5, and is it correct?
3
Which sign means “larger than or equal to”?
4
Which sign must change in the program to get the smaller number?