Python’s double slash (//
) operator performs floor division.
What exactly is floor division?
Floor division is a normal division operation except that it returns the largest possible integer. This integer is either less than or equal to the normal division result.
In code, it looks like this:
# Regular python division
8 / 3. # 2.6666666
# Floor division
8 // 3. # 2
Some languages perform floor division by default when dividing integers, like Go and (surprisingly) Ruby. In Python, you have to use //
.
Note: floor division always rounds down, not towards 0
. It’s a possible gotcha if you’re working with negative numbers:
# Regular python division
-8 / 3. # -2.6666666
# Floor division always rounds down
-8 // 3. # -3
Python