If I want to find the sum of the digits of a number, i.e.:
932
14
, which is (9 + 3 + 2)
def digitsum(n):
result = 0
for i in range(len(str(n))):
result = result + int(str(n)[i:i+1])
return(result)
"result" is initialized with 0.
Inside the for loop, the number(n) is converted into a string to be split with loop index(i) and get each digit. ---> str(n)[i:i+1]
This sliced digit is converted back to an integer ----> int(str(n)[i:i+1])
And hence added to result.