0

I need help with a pro challenge question.

I need to modify this code to sum all the numbers that are run through the loop starting with the input number. n = int(input()) length = 0 while n > 0: n //= 10 length += 1 print(length)

28th Nov 2020, 7:07 PM
Kevin Grothe
4 odpowiedzi
+ 1
Question is not clear... Your code does, finding number of digits in input number.. What it means "sum all numbers run through loop"? Do you mean finding sum of all digits of number? If yes, take another variable, and before n//10 add reminder of n%10 to sum. sum=n%10 n//=10 print(length, "sum=", sum)
28th Nov 2020, 7:27 PM
Jayakrishna 🇮🇳
+ 1
It may be easier in python to just use built-in types and functions to convert to your answer. For instance to get the length or number of digits entered you could just use len() on the input number. To get the sum of the individual digits you can convert the input to a list and then map the list to ints then sum() the new mapped list. input = 12345 print(sum(map(int, list(input())))) output = 15
28th Nov 2020, 7:47 PM
ChaoticDawg
ChaoticDawg - avatar
0
Jayakrishna🇮🇳 Awesome that solved it! But could you explain how this works? I’m not understanding what n//10 is doing and how this outputs to the correct output
28th Nov 2020, 8:42 PM
Kevin Grothe
0
If input n = 1234 sum=0 1) sum+= n%10 = 1234%10 => sum=4, n = n//10=>n=1234//10=> n= 123 2) sum+= n%10 = 123%10 => sum=4+3=7, n = n//10=>n=123//10=> n= 12 3) sum+= n%10 = 12%10 => sum=7+2=9, n = n//10=>n=12//10=> n= 1 4) sum+= n%10 = 1%10 => sum=9+1=10, n = n//10=>n=1//10=> n= 0 n>0 false, so loop stops now, sum =10, length=4, n=0 Hope it clears.. Kevin Grothe
28th Nov 2020, 9:58 PM
Jayakrishna 🇮🇳