2. Floor division and modulo

// is floor division and % is modulo (the remainder). Both are binary operators:

ExpressionResultWhy
7 // 232 fits into 7 three times
7 % 211 is left over
8 // 24the division is exact
8 % 20nothing 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.

#01

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.

#02

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.

#03

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.

#04

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.

#05

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.