Summing digits Python exercise [SPOILER]
Hello everyone, So I was stuck on this exercise and, not gonna lie, found a answer here in the Discuss section. So here's the exercise and code: The given program calculates and outputs the number of digits in a given number using a while loop. During each iteration, the loop uses floor division to divide the given number by 10, thus dropping one digit. The process continues until the number has no more digits (n>0). You need to change the code to calculate and output the sum of all digits of the input number. Sample Input 643 Sample Output 13 Explanation The sum of the digits of 643 is 6+4+3 = 13. n = int(input()) length = 0 sum = 0 while n > 0: length = n % 10 # so here we 'mod' n by 10 sum += length # sum = sum + length n //= 10 # n = n // 10 (floor() division) print(sum) Actually, I can't understand how the code adds all the input numbers. Thank you for your understanding