Practical lesson: arithmetic operations
The main method of the practical lesson is using // and % as a pair: // gives the biggest unit and % gives what is left; the same can be repeated for the rest. For example, when splitting seconds into hours, minutes and seconds, t // 3600 is the hours, t % 3600 is the seconds left after the hours; dividing it by 60 gives the minutes and the remainder is the seconds. To get the digits of a three-digit x, x // 100 is the hundreds, x // 10 % 10 the tens and x % 10 the ones. Before writing the program test it by hand with a small number: 7385 seconds must be 2 hours 3 minutes 5 seconds. A comment can be written after the # sign to explain the code, and Python does not run it. Do not forget to give the result with units of measurement.
| We find | Expression |
|---|---|
| hours | t // 3600 |
| minutes | t % 3600 // 60 |
| seconds | t % 60 |
At a school evening a video’s running time of 4500 seconds had to be shown in hours, minutes and seconds. An organiser used division and remainder and wrote it clearly as 1 hour 15 minutes.
Programmers, technicians and analysts show a large amount in hours, minutes or other units.
Work out hours, minutes and seconds for another number, such as 5400 seconds, on paper. Use division and remainder in turn.
1t = int(input()) 2h = t // 3600 3m = t % 3600 // 60 4s = t % 60 5print(h, m, s)
2 3 5
1x = int(input()) 2a = x // 100 3b = x // 10 % 10 4c = x % 10 5print(a + b + c, a * b * c)
12 42
“Chain of units”: the group chooses the length of something in centimetres (for example 538 cm) and splits it into metres and centimetres; then it tests the program by changing the number several times.