Python Division, Floor Division and Remainder
Three division operations
Use / for ordinary division: two integers give a float. Use // for floor division: for integers the result is an integer rounded toward negative infinity. Use % for the remainder associated with floor division. With a positive divisor, the integer remainder is zero or positive and smaller than the divisor.
The outputs are 3.4, 3, and 2: a fractional quotient, three full groups, and two left over.
Negative operands change the floor
print(-17 // 5)print(-17 % 5)print(17 // -5)print(17 % -5)The floor of −3.4 is −4, not −3. For nonzero integer b, the identity a == (a // b) * b + a % b holds; == means equality here. A nonzero remainder has the divisor’s sign. For example, −17 equals −4 × 5 + 3.
Pack complete boxes
items = 29capacity = 6print(items // capacity)print(items % capacity)You can fill four boxes, with five items left. The related built-in divmod() returns both results together; unpacking that pair is covered later.
A zero divisor is invalid
This example intentionally raises ZeroDivisionError, as do / and % with a zero divisor. Check that the input contract guarantees a nonzero divisor; handling invalid inputs in code is covered later.
Practice
Find the number of complete groups and leftover items when 41 items are divided into groups of eight. Repeat with -41 and explain the quotient and remainder.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Division and signed remainders
Check your understanding of division and remainder.
What is printed?
print(12 / 3)What is printed?
print(-19 // 5)What is printed?
print(-19 % 5)How many items remain after filling complete boxes of 7 from 31 items?
What happens when this code runs?
print(8 % 0)