Sum of digits in a number

This program is much similar to this one: Find product of digits in a number. The only difference is instead of multiply we have to perform addition here.

Logic

First of all, we are declaring one variable sum with value 0, we are going to use this variable to store the sum of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.

The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to add it into variable sum and store the result again in variable sum.

After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simply print the variable sum containing the sum of all digit.

Program

# Take input from user
num = int(input("Enter any number : "))

temp = num
total = 0;

while(temp != 0):

    total = total + (temp % 10);

    # Remove last digit from temp.
    temp = int(temp / 10)

print("\nSum of all digits in", num, ":", total)

Output

Enter any number : 123456
Sum of all digits in 123456 : 21