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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.