2. Floor division and modulo
// is floor division and % is modulo (the remainder). Both are binary operators:
| Expression | Result | Why |
|---|---|---|
7 // 2 | 3 | 2 fits into 7 three times |
7 % 2 | 1 | 1 is left over |
8 // 2 | 4 | the division is exact |
8 % 2 | 0 | nothing is left over |
Floor division rounds down to the nearest whole number. For negative results, "down" means toward negative infinity:
Modulo returns the remainder, and it is 0 when the division is exact:
The two operators are related: a == (a // b) * b + (a % b).
Because an even number has no remainder when divided by 2, n % 2 == 0 is True when n is even.
Coming from JavaScript? // is Math.floor(a / b). % follows the sign of the divisor, so -7 % 3 is 2, not -1 as in JS.
Floor division
Use floor division (//) to divide 7 by 2, and print the result. Floor division keeps only the whole part.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Floor division rounds down
Use floor division (//) to divide -7 by 2, and print the result. For negative results, rounding down means moving toward negative infinity.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remainder
Use modulo (%) to find the remainder of dividing 7 by 2, and print it.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Check if a number is even
Store 10 in a variable named number. Use modulo (%) and == to check whether dividing number by 2 leaves a remainder of 0, then print the result.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Split seconds into minutes
Store 125 in a variable named total. Print how many whole minutes it contains using // 60, then print the remaining seconds using % 60. Print each value on its own line.
Print exactly:
Create a free account to save your progress and unlock chapter 2.