# 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
``````

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

#### Best Solution

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 : 10 / 3
Out: 3

In : 10 // 3
Out: 3

In : from __future__ import division

In : 10 / 3
Out: 3.3333333333333335

In : 10 // 3
Out: 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 : n = 50

In : n += 10

In : n
Out: 60

In : n -= 20

In : n
Out: 40

In : n //= 10

In : n
Out: 4
``````

Category: Uncategorized