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: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):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 ofnand performs the operation before the equal sign with the following variable as the second argument, returning the result inton. For example: