+ 2

Python Course - while loops

Hi Guys ! I'm actually on the Python course and I'm looking for the solution of a pro problem in the while loops section. The problem ask to calculate the sum of all the digits of an integer input. And my solution for me was that : n = int(input()) sum = 0 length = 0 while n > 0: n //= 10 length += 1 sum += length print(sum) For me, the variable n is for the input of the users. Lenght is for calculate the number of digits. I understand that. So I create a variable sum for calculate the sum of all the lenght who are generate by the while loop. With that, I would have the result that the problem want. But it's not the case and I don't know why. Someone can explain me my error ? Thanks !

28th Aug 2020, 3:45 PM
Greg GS
Greg GS - avatar
7 odpowiedzi
+ 3
Okay ! My error was to consider the lenght like the digit in my head but I see with your example that it two things totally different ! Thanks for your help guys !
28th Aug 2020, 4:05 PM
Greg GS
Greg GS - avatar
+ 2
The sum of all lengths differs from the sum of all digita , what you should've wrote instead is while n>0: sum+=n%10 length+=1 n//=0 % is the mod operation which will give you the last digit when you use it with 10 you can test it here https://code.sololearn.com/cySw7yFuI5bD/?ref=app
28th Aug 2020, 3:53 PM
Med Anis Jbara
Med Anis Jbara - avatar
+ 1
Greg GS You could also use a list comprehension to split and add them. number = int(input()) add = sum( [int(x) for x in str(number)] ) print(add) What I have done is convert the number to a sting, loop over each element and turn them back to an integer then used the sum function. Also, try not to use "sum" as a variable name. Happy Coding 😀
28th Aug 2020, 9:01 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 1
Wow great example too Tomiwa Joseph ! But why not to use sum as a variable name ?
28th Aug 2020, 9:04 PM
Greg GS
Greg GS - avatar
+ 1
Greg GS You can use it as long as you won't use the sum function in your code. Example: sum = 4 print(sum([1,2,3])) You get an error because you have overwritten the sum function with 4. Python won't understand print(4([1,2,3]))... I don't understand it either 😃
28th Aug 2020, 9:15 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 1
And I don't understand it too. I get it. Thanks for your help !
28th Aug 2020, 9:17 PM
Greg GS
Greg GS - avatar