Monday, October 25, 2010

Sum of digits

#sumofdigits.py
#Finds the sum of digits of entered number

num=int(input('Enter a number:'))
sum_of_digits=0
for n in str(num):
    sum_of_digits+=int(n)
print(sum_of_digits)

A pretty short program for finding the sum of digits of a number. As you can see, the program converts the integer to a string, and then finds the sum of digits by extracting each digit(as string), converting the digit to integer, and adding it.

Do share with us any alternative ways you know to perform this same task.