+ 1

Hardcore stuck at python 27.2 summing digits

Hello guys i am hardcore stuck at this code cant figure it out its the 6th day i cant find any solution pls help n = int(input()) length = 0 while n > 0: n //= 10 length += 1 print(length)

15th Feb 2021, 6:29 AM
Srecko Mitrovic
Srecko Mitrovic - avatar
3 Antworten
+ 8
If you want to calculate the sum of digits using math, look at the modulus operator. For example, here: n = int(input()) length = 0 digit_sum = 0 while n > 0: digit_sum += n % 10 # add value of least significant base 10 digit. n //= 10 length += 1 # not really needed unless you also want to count the number of digits. print(digit_sum) Here is another way to calculate it. It uses list comprehension and Python's sum function: digit_sum = sum([int(digit) for digit in str(n)]) print(digit_sum)
15th Feb 2021, 6:40 AM
Josh Greig
Josh Greig - avatar
+ 1
You can do it that way too: def getSum(n): sum = 0 while (n != 0): sum = sum + (n % 10) n = n//10 return sum n = int(input()) print(getSum(n))
15th Nov 2021, 9:12 PM
Stefan Bartl
Stefan Bartl - avatar