Floor Division Operator in Python (//)

The Floor Division Operator (//), also known as integer division, is used to divide two numbers and round the result down to the nearest whole integer. It strips away the fractional part of the quotient, making it incredibly useful for tasks like chunking data, finding indices, or calculating exact quantities.
1. Basic Integer Floor Division
When you use // with two integers, the fractional part is simply discarded, leaving only the whole number.
# Standard vs Floor Division
print(10 / 3) # Output: 3.3333333333333335
print(10 // 3) # Output: 3
# Clean division
print(15 // 5) # Output: 3
2. Float Floor Division
If one or both operands are floats, Python will still perform the floor division mathematically, but the result will be returned as a floating-point type (with a .0 at the end).
# Using floats with floor division
print(10.5 // 3) # Output: 3.0
print(12 // 4.5) # Output: 2.0 (Because 12 / 4.5 is 2.666...)
print(15.5 // 4.5) # Output: 3.0
3. The Negative Number "Gotcha"
This is one of the most common pitfalls for beginners! Floor division always rounds down towards negative infinity, not towards zero. If the result is negative, it rounds to the next lowest integer.
# Positive numbers round normally
print(10 // 3) # Output: 3
# Negative numbers round DOWN (away from zero)
print(-10 // 3) # Output: -4 (Because -3.33 rounded down is -4)
print(10 // -3) # Output: -4
math.trunc() or int() functions instead of the // operator.
4. Complex Numbers
With complex numbers, the floor division operation throws a TypeError (unsupported operand type). The following errors may be observed if any one operand is a complex number.
- TypeError: unsupported operand type(s) for //: ‘complex’ and ‘int’
- TypeError: unsupported operand type(s) for //: ‘complex’ and ‘float’
- TypeError: unsupported operand type(s) for //: ‘int’ and ‘complex’
- TypeError: unsupported operand type(s) for //: ‘float’ and ‘complex’
5. Common Errors To Avoid
# print(15 // 0) # Raises ZeroDivisionError: integer division or modulo by zero
💡 Interesting Facts
- The `divmod()` function: Python has a built-in function called
divmod(a, b)that returns a tuple containing both the floor division result and the remainder simultaneously:divmod(10, 3)returns(3, 1). - No Complex Numbers: Unlike addition, subtraction, multiplication, and true division, floor division (
//) does not support complex numbers. Attempting to use it on a complex number will raise aTypeError. - Performance: For large integers in algorithms (like binary search), integer division is highly optimized in Python and avoids the floating-point precision issues that standard division might introduce.