Let’s rule out what we cannot do, then work toward what we can do…
Can we iterate over an integer?
>>> for x in 123456789:
print (x)
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
for x in 123456789:
TypeError: 'int' object is not iterable
>>>
That rules out being able to simply add the digits in a loop. But does it, really?
>>> for x in str(123456789):
print (x)
1
2
3
4
5
6
7
8
9
>>>
Now we have a basis for iteration, and we know how to keep a running sum… a = a + x
. However since x
is a string, we will hit a snag…
>>> total = 0
>>> for x in str(123456789):
total += x
Traceback (most recent call last):
File "<pyshell#36>", line 2, in <module>
total += x
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
>>>
No problem, since we know about the str()
constructor, we must know about the int()
constructor, too.
>>> total = 0
>>> for x in str(123456789):
total += int(x)
>>> print (total)
45
>>>
So we used three operators, =
, in
, and +=
; one loop, for
, and two built-in’s, str()
, and int()
. This is the simplest approach to this problem using basic arithmetic.
The less naive approach uses maths, but very few learners will arive at this one, since some concepts are still pretty new, if not completely foreign.
// => floor division
% => modulo (remainder)
Modulo will give us the last digit if our divisor (modulus) is 10…
123 % 10 => 3
Floor division will reduce it by one digit if we divide by 10…
123 // 10 => 12
So now we set up a loop to carry out the cycles until we reduce the number down to zero…
>>> total = 0
>>> x = 123456789
>>> while x > 0:
total += x % 10
x //= 10
>>> print (total)
45
>>>
Now we get to your method, that of progressively decreasing by powers of 10 and dividing. Something to consider,
n = len(str(int(x)))
x
is already stipulated to be an integer so the int()
function is not needed. We can however make use of the length, as you have deduced.
>>> total = 0
>>> x = 123456789
>>> for n in range(len(str(x)) - 1, -1, -1):
y = x // 10 ** n
total += y
x -= y * 10 ** n
>>> print (total)
45
>>>
We’ve seen how the solutions have grown in complexity and one must ask, which of these is the simplest?