3.2.3 - Arithmetic and division (Python)
Arithmetic expressions calculate new values from stored data. You will distinguish ordinary division from whole-group counts and remainders, and choose Python operators that match a problem.
Arithmetic expressions
An arithmetic expression describes a calculation rather than just naming its final answer.
Python uses + for addition, - for subtraction and * for multiplication. Suppose a club starts with 20 badges, gives away 3 and receives 2 packs containing 6 badges each.
badge_count = 20 - 3 + 2 * 6
print(badge_count)
Multiplication is evaluated before addition and subtraction, so the expression gives 29. Writing (20 - 3 + 2) * 6 instead gives 114, a different calculation: the brackets change which value is multiplied. Use brackets to express the intended grouping clearly rather than relying on a reader to guess it.
For a delivery bill, item_count * item_price + delivery_charge first calculates the items' cost and then adds the one delivery charge. (item_count + delivery_charge) * item_price incorrectly treats a monetary charge as an item count. Correct syntax does not guarantee correct modelling of the problem.
Real division, integer division and remainders
Division can answer different questions: the average share, the number of complete groups or what remains after those groups are made.
| Python operator | Meaning for non-negative counts | 11 divided by 2 |
|---|---|---|
/ | Real division, retaining a fractional part | 5.5 |
// | Integer quotient: number of complete groups | 5 |
% | Remainder after complete groups | 1 |
AQA pseudocode writes DIV and MOD for the latter two; Python uses // and %. Technically // floors the quotient, so avoid assuming it truncates towards zero for negative values. Our packing examples use non-negative quantities.
For a non-negative integer quantity and a positive group size:
quantity = (quantity // group_size) * group_size + quantity % group_size
With 23 bottles and boxes holding 6, 23 // 6 gives 3 full boxes. Those contain 18 bottles, and 23 % 6 gives the 5 bottles left over. 23 / 6 gives about 3.8333, which is unsuitable as a count of full boxes but might be useful in a numerical calculation. If every bottle must be shipped, the leftover bottles need one extra box: integer division alone would undercount the required boxes.
Predict the sandbox's complete-box and leftover counts. Run it, then change the quantity to an exact multiple of the box size and check what happens to the remainder.
Packing complete boxes
{"code":"bottle_count = 23\nbox_size = 6\nprint("Full boxes:", bottle_count // box_size)\nprint("Left over:", bottle_count % box_size)","instructions":"Predict and run. Change bottle_count from 23 to 24 and run again. Explain why the leftover count becomes zero."}
Choose / for a real-valued division result, // for the integer quotient and % for the remainder. Decide what the problem needs before selecting the operator.