Python floor division is done with the // operator. A floor division is a sort of division in which the outcome is “floored,” or rounded to the closest whole integer. After dividing two numbers, this operator eliminates any decimal portion and rounds the output to the closest integer.
How it works:
# Example of floor division
result = 7 // 2
print(result) # Output: 3
How It Works:
- Normal Division (
/) returns a floating-point result:
7 / 2 # Output: 3.5
- Floor Division (
//) discards the decimal part and returns only the integer part of the quotient:
7 // 2 # Output: 3
When to Use //
- When you need only the whole number result and want to discard the decimal.
- Commonly used in loops or scenarios where whole numbers are needed for indexing or counting.
Examples with Negative Numbers:
With negative numbers, // will still round down (or toward negative infinity), so the result might be lower than expected:
# Positive result
10 // 3 # Output: 3
# Negative result
-10 // 3 # Output: -4
Summary
In short, the // operator gives the integer part of the division result, making it handy for situations where only the whole number is needed without rounding.