+ 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 !
6 Antworten
+ 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 !
+ 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
+ 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 😀
+ 1
Wow great example too Tomiwa Joseph !
But why not to use sum as a variable name ?
+ 1
And I don't understand it too. I get it. Thanks for your help !