Arithmetic in Code: Integer Division and Remainder
The arithmetic a program actually offers, including whole-number division and the remainder, and the order operators are applied in.
What a learner can do afterwards
- Work out the result of an expression mixing multiplication, addition and brackets
- Use whole-number division and remainder to split a total, such as seconds into minutes and seconds
- Say which operator runs first without running the code
1 · Read
Your code can add, subtract, multiply and divide like your calculator. Two extra tools split division in two: // keeps the whole part and throws the leftover away, while % keeps only the leftover. So 17 // 5 is 3, and 17 % 5 is 2.
Turn 250 seconds into minutes and seconds the way code does. 250 // 60 is 4 whole minutes, and 250 % 60 is the 10 seconds left over. Together they rebuild the total, since 4 times 60 plus 10 is 250.
When operators mix, brackets run first, then multiply, divide, // and %, then add and subtract last. Operators on the same level run left to right. That is why 5 + 2 * 3 is 11, while (5 + 2) * 3 is 21, and 9 - 3 + 2 is 8, not 4. Say which operator runs first before you run the code.
Ask yourself what each piece keeps. // keeps the wholes and drops the rest, % drops the wholes and keeps the rest. That holds for positive numbers. With a negative number, Python's // rounds down, so -7 // 2 is -4.
Brackets first, then multiply and divide, then add; // keeps wholes and % keeps the leftover.
The rewritten reading was written for this dataset. Practice items adapted from WeBWorK Open Problem Library problems by RA Cruz (The College of Idaho); Utah ww group (University of Utah); Rick Lynch (University of Missouri-Columbia); Carl Yao (PCC); Arizona State University contributors (CC BY-NC-SA 3.0).
2 · Watch
En anglaisTake it off screen
Where it sits
20 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.