Sum of Digits Program in Python

This is a Python Program to find the sum of digits in a number.

Problem Description

The program takes in a number and finds the sum of digits in a number.

Problem Solution

1. Take the value of the integer and store in a variable.
2. Using a while loop, get each digit of the number and add the digits to a variable.
3. Print the sum of the digits of the number.
4. Exit.

Program/Source Code

Here is the source code of the Python Program to find the sum of digits in a number. The program output is also shown below.

 
n=int(input("Enter a number:"))
tot=0
while(n>0):
    dig=n%10
    tot=tot+dig
    n=n//10
print("The total sum of digits is:",tot)
Program Explanation

1. User must first enter the value and store it in a variable.
2. The while loop is used and the last digit of the number is obtained by using the modulus operator.
3. The digit is added to another variable each time the loop is executed.
4. This loop terminates when the value of the number is 0.
5. The total sum of the number is then printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter a number:1892
The total sum of digits is: 20
 
Case 2:
Enter a number:157
The total sum of digits is: 13

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.