In Python, a // b
is defined as floor(a/b), as opposed to most other languages where integer division is defined as trunc(a/b). There is a corresponding difference in the interpretation of a % b
= a - (a // b) * b
.
The reason for this is that Python's definition of the %
operator (and divmod
) is generally more useful than that of other languages. For example:
def time_of_day(seconds_since_epoch):
minutes, seconds = divmod(seconds_since_epoch, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
return '%02d:%02d:%02d' % (hours, minutes, seconds)
With this function, time_of_day(12345)
returns '03:25:45'
, as you would expect.
But what time is it 12345 seconds before the epoch? With Python's definition of divmod
, time_of_day(-12345)
correctly returns '20:34:15'
.
What if we redefine divmod
to use the C definition of /
and %
?
def divmod(a, b):
q = int(a / b) # I'm using 3.x
r = a - b * q
return (q, r)
Now, time_of_day(-12345)
returns '-3:-25:-45'
, which isn't a valid time of day. If the standard Python divmod
function were implemented this way, you'd have to write special-case code to handle negative inputs. But with floor-style division, like my first example, it Just Works.