Problem overview
This is the first version of the Report Card project. A student took three tests, stored in test1, test2 and test3. Your job is to compute the average score and keep it in a variable named average, as a whole number.
With the starter values 85, 92 and 78, the three scores add up to 255, and 255 divided by 3 is exactly 85. The expected result reads Average: 85. The lesson's tests print the label and the value for you, so the program itself prints nothing: it only has to create the variable.
Approach: add first, then divide
An average is the sum of the values divided by how many there are. Here that means the sum of three tests divided by 3. The only Python-specific choice is which division to use.
Python has two division operators. The single slash / always gives a float, even when the numbers divide evenly. The double slash // is integer division: it drops the fractional part and gives a whole number. The lesson asks for //, so that the report card shows 85 and not 85.0.
255 // 3 -> 85
255 / 3 -> 85.0
Step by step
- Add the three tests. Put
test1 + test2 + test3inside parentheses, so that the sum is complete before anything divides it. - Divide by 3 with
//. The number 3 is how many tests there are. - Store the result in
average, below the three starter variables.
The solution in Python
test1 = 85
test2 = 92
test3 = 78
average = (test1 + test2 + test3) // 3
The parentheses matter. Python applies // before +, exactly as it applies * before + in ordinary arithmetic. Without them, test1 + test2 + test3 // 3 would divide only test3 by 3 and then add the result to the other two scores. With the starter values that expression gives 85 + 92 + 26 = 203, which is not an average of anything.
Edge cases and common mistakes
- Totals that don't divide evenly. Integer division rounds down. Scores of 70, 71 and 71 add up to 212, and
212 // 3is 70 even though the exact average is about 70.67. A score of 100, 100 and 99 gives 99. The rounding is always toward the lower number, never to the nearest. - Using
/. For the starter data,(test1 + test2 + test3) / 3gives85.0, a float. The value looks almost right but prints with a decimal point, so the output no longer readsAverage: 85. - Forgetting the parentheses. This produces a number that is too large, as shown above, with no error message to warn you.
- Dividing by the wrong count. The 3 in the formula is the number of tests. If the number of tests changes, the 3 has to change with it.
Key takeaways
- The average is the sum divided by the count.
//gives a whole number, rounded down;/gives a float.- Parentheses make the sum happen before the division.
