Python program to find the sum of digits of a number

Description: Write a Python program to find the sum of the digits of a number.

Rules and hints:

  • Use % 10 to get the last digit.
  • Use // 10 to remove the last digit.

Python program for the sum of digits

num = 1234
total = 0

while num > 0:
    total += num % 10
    num = num // 10

print("Sum of digits:", total)

Output:

Tutorials Class - Output Window

Sum of digits: 10

How it works

  • 1234 % 10 is 4, and then 1234 // 10 is 123.
  • The loop continues with 123, 12 and 1, adding 3, 2 and 1.
  • So the total is 4 + 3 + 2 + 1 = 10. The loop stops when the number becomes 0.

Learn more in Python While Loop.


Learn more about the similar topics:
Tutorials
Python Conditional Statements
Python While Loop
Python for loop
Python Jump Statements
Exercises & Assignments
Python program to check even or odd number
Python program to find the largest of three numbers
Python program to check leap year
Python program to print multiplication table
Python program to find factorial of a number
Python program to print Fibonacci series
Python program to check prime number
Interview Questions & Answers
No Content Found.