Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 1 min read

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 (di

Vinoth
Vinoth

Posted on Nov 23 β€’ Edited on Nov 23

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

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.