def sum_of_digits(n): sum = 0 while (n != 0): sum = sum + int(n % 10) n = int(n/10) return sum
Here is what the above code is Doing:
1. We have a while loop that runs until n is equal to 0.
2. We add the last digit of n to the sum.
3. We divide n by 10 to remove the last digit.
4. We repeat the process until n is equal to 0.
We can also use recursion to solve this problem.