+ 3

Question on While Loops

Here's my question, from the PythonCore lesson on While loops: while Loops The given program calculates and outputs the number of digits in a given number using a while loop. n = int(input()) length = 0 while n > 0: n //= 10 length += 1 print(length) PY 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. You can get each digit of the number by modulo dividing (%) it by 10 during each iteration. And here's the solution. n = int(input()) sum = 0 while N>0: num = n%10 sum += num n //= 10 print(sum) Please explain how n%10 gives the number of digits in the input, and also what the following line of code means: n //= 10 I know it resets the while loop but that's it.

22nd Mar 2022, 12:25 AM
Dan
Dan - avatar
3 Réponses
+ 4
Daniel Bouffard Modulus operator (%) returns reminder so if n = 643 then n % 10 would return 3 because 64 * 10 + 3 = 643 n //= 10 means n = n // 10 Here // is floor division which returns whole integer number so 643 // 10 would be 64 If n = 643 num = 643 % 10 = 3 sum = sum + 3 = 0 + 3 = 3 n //= 10 => 64 So now n = 64 Again: num = 64 % 10 = 4 sum = sum + 4 = 3 + 4 = 7 n //= 10 => 6 So now n = 6 num = 6 % 10 = 6 sum = 7 + 6 = 13 n //=10 => 0 Now loop will stop because n = 0 So sum is = 13
22nd Mar 2022, 1:11 AM
A͢J
A͢J - avatar
+ 3
I think I get it thanks to your clear explanation of the logic. I spent a couple of hours trying to figure this one out. Thank you!!
22nd Mar 2022, 1:50 AM
Dan
Dan - avatar
+ 1
n = int(input()) sum = 0 while n > 0: sum += n % 10 n //= 10 print(sum)
22nd Mar 2022, 8:32 AM
CodeStory
CodeStory - avatar