Write a Program in Python to find sum of digits of a given number.

i=int(input("Enter Number to find sum of digits:"))
sum=0
while(i>0):
    sum=sum+i%10
    i=i//10
print("Sum of digits=",sum)

Output:

Enter Number to find sum of digits:123
Sum of digits= 6

Explanation:

What does this program do?
It finds the sum of digits of a number entered by the user.

Example:
If the number is 123, the sum is 1 + 2 + 3 = 6

Line-by-Line Explanation
1. Input from user
i = int(input(“Enter Number to find sum of digits: “))

  • Takes a number from the user
  • Converts it to an integer
  • Stores it in variable i

Example input:
Enter Number to find sum of digits: 123

2. Initialize sum
sum = 0

  • This variable will store the final sum of digits

3. While loop
while(i > 0):

  • Loop runs until the number becomes 0

4. Get last digit
sum = sum + i % 10

  • i % 10 gives the last digit of the number

Example:

  • 123 % 10 = 3
  • 12 % 10 = 2
  • 1 % 10 = 1

5. Remove last digit
i = i // 10

  • Removes the last digit using integer division

Example:

  • 123 // 10 = 12
  • 12 // 10 = 1
  • 1 // 10 = 0
i valuei % 10sum value
12330 + 3 = 3
1223 + 2 =5
115 + 1 = 6
0loop ends


6. Output
print(“Sum of digits =”, sum)

Output:

Sum of digits = 6

Final Result

Enter Number to find sum of digits:123
Sum of digits= 6

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top