How to separate the digits of a whole number and add them together? – Python


How to separate the digits of a number and add them, for example: 123 -> 1 + 2 + 3 = 6

How to do this though, do this using arithmetic operators. I saw a case where it was separated using operations with "//" and "%", but I didn't quite understand how to do it.


You can do it this way start with a variable for the sum using a loop to interact the digits of the number informed in example 123 at each step and done the division removing the rest of the division of the number by 10 with this extracting the last number number % 10 remainder of division 3 then divide the number by 10 with result 12 then restart the loop 12% 10 remainder of division 2 in the case already adding to number 3 and so on.

soma = 0
numero = 123
while(numero > 0):
    soma += numero % 10
    numero = int(numero /10)
Scroll to Top