In Python, the //
operator performs floor division. This means it divides two numbers and rounds down the result to the nearest whole number. The process of rounding down is called “flooring,” hence the name “floor division.”
Syntax
The syntax for floor division is straightforward:
result = numerator // denominator
Where numerator
is the number to be divided, and denominator
is the number by which you divide.
How Does Floor Division Work?
Integer Division
When both operands are integers, the result of the //
operator is also an integer. It divides the first operand by the second and then floors the result to the nearest integer towards negative infinity.
Example 1: Positive Integers
result = 7 // 2 print(result) # Output: 3
In this example, 7 divided by 2 is 3.5. Flooring 3.5 gives us 3.
Example 2: Negative Integers
result = -7 // 2 print(result) # Output: -4
Here, -7 divided by 2 is -3.5. Flooring -3.5 towards negative infinity gives us -4.
Floating-Point Division
Example 3: Float and Integer
result = 7.0 // 2 print(result) # Output: 3.0
In this example, 7.0 divided by 2 is 3.5. Flooring 3.5 gives us 3.0 (float).
Example 4: Integer and Float
result = 7 // 2.0 print(result) # Output: 3.0
Here, 7 divided by 2.0 is 3.5. Flooring 3.5 gives us 3.0 (float).
Negative Floats
Floor division with negative floats follows the same principle, rounding towards negative infinity.
Example 5: Negative Float
result = -7.0 // 2 print(result) # Output: -4.0
In this example, -7.0 divided by 2 is -3.5. Flooring -3.5 gives us -4.0 (float).
Practical Use Cases
Floor division is particularly useful when you need an integer result from division, such as when working with indices in a list or when ensuring the result is a whole number for further computations.
Example 6: Using Floor Division for Indexing
Imagine you have a list of items and want to divide it into two equal parts:
items = [1, 2, 3, 4, 5, 6] half_length = len(items) // 2 print(half_length) # Output: 3 first_half = items[:half_length] second_half = items[half_length:] print(first_half) # Output: [1, 2, 3] print(second_half) # Output: [4, 5, 6]
In this example, len(items) // 2
calculates the halfway point of the list, allowing us to split it into two parts.
Example 7: Ensuring Whole Number Results
If you’re calculating the number of full boxes needed to pack items, floor division can help:
total_items = 17 items_per_box = 5 full_boxes = total_items // items_per_box print(full_boxes) # Output: 3
Here, 17 // 5
calculates the number of full boxes required, ignoring any leftover items.
Comparisons with Other Operators
/
(True Division): This operator performs standard division and always returns a float, even if both operands are integers.%
(Modulo): This operator returns the remainder of a division operation.divmod(a, b)
: This function returns a tuple containing the result ofa // b
anda % b
.