Python – Exercise on Summing Digits | What’s with n // = 10

By | October 22, 2023

Possible Duplicate:
What is the reason for having ‘//’ in Python?

While trying to do an exercise on summing digits, I stumbled on this solution:

def sum_digits(n):
   import math
   total = 0
   for i in range(int(math.log10(n)) + 1):
      total += n % 10
      n //= 10
   return total

My question is, what does the second to last line do? How is that proper syntax?

That implements what is called floor division. Floor division (indicated by // here) truncates the decimal and returns the integer result, while ‘normal’ division returns the answer you may ‘expect’ (with decimals). In Python 3.x, a greater distinction was made between the two, meaning that the two operators return different results. Here is an example using Python 3:

>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3

Prior to Python 3.x, there is no difference between the two, unless you use the special built-in from __future__ import division, which then makes the division operators perform as they would in Python 3.x (this is using Python 2.6.5):

In [1]: 10 / 3
Out[1]: 3

In [2]: 10 // 3
Out[2]: 3

In [3]: from __future__ import division

In [4]: 10 / 3
Out[4]: 3.3333333333333335

In [5]: 10 // 3
Out[5]: 3

Therefore when you see something like n //= 10, it is using the same +=/-=/*=/etc syntax that you may have seen, where it takes the current value of n and performs the operation before the equal sign with the following variable as the second argument, returning the result into n. For example:

In [6]: n = 50

In [7]: n += 10

In [8]: n
Out[8]: 60

In [9]: n -= 20

In [10]: n
Out[10]: 40

In [11]: n //= 10

In [12]: n
Out[12]: 4

Category: Uncategorized