In Python, a // b
is defined as floor (a / b), unlike 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 the Python definition of the %
(and divmod
) operator is usually more useful than the definition of other languages. For instance:
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)
Using this function, time_of_day(12345)
returns '03:25:45'
, as you would expect.
But what time is 12345 seconds before the era? Using the Python definition of divmod
, time_of_day(-12345)
correctly return '20:34:15'
.
What if we override divmod
to use the definition of C /
and %
?
def divmod(a, b): q = int(a / b)
Now time_of_day(-12345)
returns '-3:-25:-45'
, which is not a valid time of day. If the standard Python function divmod
were implemented this way, you would have to write special code to handle negative inputs. But with dividing the floor style, as in my first example, it just works.
source share