Python Program to calculate the sum of digits in a number

In this simple python program, we have to find the sum of digits in a number. It is a beginner-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

How to find the sum of digits in a number?

In this  basic python program on numbers, we need to calculate the sum of digits of a number, which means, take a number 123 and we have to find the sum as ' 1 + 2 + 3 = 6 '

To apply this logic in this simple python program, we need to open an while loop until the number is less than zero. We have to take the digit from the number by using the mod operator and calculate the sum in python as sum + digit. Then we have to remove one digit from the number by dividing the number by 10. Finally, we print the result after all the iterations of the while loop in python language.

ALGORITHM

STEP 1: Accept the user's input using the input function and convert that string to an integer using int() in the Python programming language.

STEP 2: Initialize the sum as zero.

STEP 3: Open a while loop till the number is less than zero.

STEP 4: Take one digit from the number using the mod operator.

STEP 5: Calculate the sum as sum + digit.

STEP 6: Remove the digit from the number by dividing the number by 10.

STEP 7: Print the result using the print statement.

Python Source Code

                                          n=int(input("Enter a number:"))

sum=0

while(n>0):

    dig=n%10

    sum=sum+dig

    n=n//10

print("The sum of digits in the number is:",sum)
                                      

OUTPUT

Enter a number : 123

The sum of digits in the number is: 6