+ 1

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

4th Apr 2021, 6:13 PM
Da Silva Miguel
Da Silva Miguel - avatar
3 Answers
+ 7
Let's take the 643 as example 1st iteration: 643 % 10 = 3 sum = 0 + 3 = 0 n //= 10 => n = 64 2nd iteration: 64 % 10 = 4 sum = 3 + 4 = 7 n //= 10 => n = 6 3rd iteration: 6 % 10 = 6 sum = 7 + 6 = 13 n //= 10 => n = 0 As n > 0 is False now, the loop ends. Final result: sum = 3 + 4 + 6 = 13 = sum of digits of 643
4th Apr 2021, 6:32 PM
XXX
XXX - avatar
+ 3
Ohhhhh Lovely! Thank you very much! Clear and precise!
4th Apr 2021, 6:35 PM
Da Silva Miguel
Da Silva Miguel - avatar
0
@xxx @Da Silva Miguel Thank you so much for that explanation! I could not figure this out for the life of me. I've understood everything in the modules so far until I got to the loops. My math skills are lacking, so I thought I was just too stupid for this. Your explanation made it clear.
31st Jan 2022, 7:38 AM
Joseph Rowe
Joseph Rowe - avatar