by BehindJava
Write a program to to Find the Sum of Digits in a Number in Python
In this tutorial we are going to learn about finding the Sum of Digits in a Number in Python.
Python Program to Find the Sum of Digits in a Number
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)
Explanation
- User must first enter the value and store it in a variable.
- The while loop is used and the last digit of the number is obtained by using the modulus operator.
- The digit is added to another variable each time the loop is executed.
- This loop terminates when the value of the number is 0.
- The total sum of the number is then printed.