DEV Community

Vinoth
Vinoth

Posted on Edited on

Sum the Digits of a Given Number - Python !

Sum the Digits of a Given Number - Python

For example, given the number 123456, the sum of its digits is 1 + 2 + 3 + 4 + 5 +6 = 21.

no=123456
sum = 0
while no >0:
    digits = no % 10  # extract last digit (12345 (digits=6)
    sum=sum+digits 
    no=no//10       # remove last digit (12345 (6) (no=12345))

print("sum of digits:",sum)

Enter fullscreen mode Exit fullscreen mode

OUTPUT=21

OR


n = 12345
sum = 0

while n > 0:
    sum += n % 10  # extract last digit
    n //= 10       # remove last digit

print("sum of digits:",sum)
Enter fullscreen mode Exit fullscreen mode

OUTPUT= 15

Top comments (0)