☰ Year plan · Communication Technology

Remainders, decisions and averages

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

The average of three numbers

ICT Prep 3 Term 1, Unit 1, Lesson 1: pp. 8–9
GoalWrite the average of three numbers in Python and avoid the bracket trap.
New words
average · the sum of the values divided by how many values there arebrackets · round brackets that make Python calculate the inside first/ · division; the result is always a decimal number// · division that keeps only the whole-number part
Explanation

The average of three numbers is their sum divided by 3. The pattern is the same as for any average: add everything, then divide by how many. The brackets matter. Python does division before addition, so a + b + c / 3 divides only c. With 50, 60 and 70 the right line gives 60.0 and the wrong one gives 133.33333333333334. Notice also that the answer is 60.0 and not 60: the sign / always gives a decimal result, even when the division comes out exactly. The sign // gives the whole-number part instead: 7 / 2 is 3.5 but 7 // 2 is 3. Some books say that you must use float for an average, but the input numbers here are read with int and the average is still right, because / does the job.

Python
1a = int(input("First mark: "))
2b = int(input("Second mark: "))
3c = int(input("Third mark: "))
4avg = (a + b + c) / 3
5print(avg)
Output
First mark: 50
Second mark: 60
Third mark: 70
60.0
Worked examples
Python
1a = 50
2b = 60
3c = 70
4print((a + b + c) / 3)
5print(a + b + c / 3)
Output
60.0
133.33333333333334
Both lines below start from the same marks. The first has brackets, so the whole sum is divided by 3. The second divides only c by 3 and then adds the rest. Always put the sum inside brackets.
Python
1print(7 / 2)
2print(7 // 2)
3print((50 + 60 + 70) // 3)
Output
3.5
3
60
Mona wants only the whole-number part. The line 7 / 2 gives 3.5, the line 7 // 2 gives 3, and the whole sum 180 divided by 3 with // gives 60 with no decimal point.
Python
1a = int(input("First mark: "))
2b = int(input("Second mark: "))
3c = int(input("Third mark: "))
4avg = (a + b + c) / 3
5print(avg)
Output
First mark: 40
Second mark: 70
Third mark: 100
70.0
Check by hand: marks 40, 70 and 100 add up to 210, and 210 divided by 3 is 70. The program shows 70.0.
Class activity

Plan a program that finds the average of the four quiz marks of an invented pupil. Write the four skills, the formula with brackets, and test it with marks 8, 6, 10 and 8. Then change the line without brackets and see by hand what is wrong.

Practice
1
Why does a + b + c / 3 not give the average?
2
What does (50 + 60 + 70) / 3 show?
3
What is 9 // 2, and what is 9 / 2?
4
A friend says an average needs float, not int, to be read. Is that right?