python – Exercise on Summing Digits | Whats with n // = 10
python – Exercise on Summing Digits | Whats with n // = 10
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
//
is the floor division operator. It always truncates the return value to the largest integer smaller than or equal to the answer.
python – Exercise on Summing Digits | Whats with n // = 10
The second to last line is a combination of operators, in a way, including an uncommon one, which is why its a little confusing.
Lets piece it apart.
First, //
in Python is floor division, which basically is division rounded down to the nearest whole number. Thus,
>>> 16//5
3
>>> 2//1
2
>>> 4//3
1
>>> 2//5
0
Finally, the =
is there because of a Python syntax that allows one to perform an operation on a variable, and then immediately reassign the result to the variable. Youve probably seen it most commonly in +=
, as:
>>> a = 5
>>> a += 7
>>> a
12
In this case, //=
means perform floor division, floor dividing the variable by the second argument, then assign the result to the original input variable. Thus:
>>> a = 10
>>> a //= 6
>>> a
1