Menu

Arithmetic Operations

Using integer division and modulo

Integer division (//) gives the whole number of times one number fits into another. Modulo (%) gives what is left over. Together they answer how many complete groups there are and what remains.

Odd, even and multiples

For any whole number, number % 2 is 0 when the number is even and 1 when it is odd, because dividing by 2 leaves either nothing or one. You can use that result to decide what happens next with selection.

Modulo also tests multiples. If a % b is 0, then a is exactly divisible by b, so it is a multiple of b. For example, 84 % 7 is 0, so 84 is a multiple of 7; 85 % 7 is 1, so it is not.

Groups, leftovers and digits

Integer division gives complete groups and modulo gives the leftovers. With 29 eggs packed 6 to a box, 29 // 6 is 4 complete boxes and 29 % 6 is 5 eggs left. A nonzero remainder means you need one more box for those 5 eggs; if the remainder were 0, the complete boxes would hold everything. Use // here, not /: 29 / 6 gives about 4.83, which is not a whole number of boxes.

Flowchart: input eggs, set per_box to 6 and boxes to eggs // per_box; if eggs % per_box is not 0, add 1 to boxes; then output boxes. Worked example: 29 // 6 = 4 full boxes and 29 % 6 = 5 left over, so 5 boxes are needed.

eggs = int(input("Number of eggs: "))
per_box = 6
full_boxes = eggs // per_box
left_over = eggs % per_box
print("Full boxes:", full_boxes)
print("Left over:", left_over)

Output when the user types 29:

Number of eggs: 29
Full boxes: 4
Left over: 5

To take digits from a whole number, number % 10 gives the last digit and number // 10 removes it. For 63, 63 % 10 is 3 and 63 // 10 is 6, so the tens digit is 6 and the units digit is 3.

Hours and minutes

A film lasts 158 minutes. 158 // 60 is 2 whole hours, and 158 % 60 is 38 minutes left over, so the film is 2 hours 38 minutes long.

Practise this