This post shows how to find the sum of digits of a number in Python — a simple exercise that's also a useful building block for other number-based problems.

Find the sum of digits of a number in Python:

Explanation:
We repeatedly extract the last digit of the number using the modulo operator % 10, add it to a running total, and then remove that digit using integer division // 10, until the number becomes 0.


Python Program to Find Sum of Digits of a Number

num = int(input("Enter a number: "))
original = num
total = 0

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

print(f"Sum of digits of {original} is {total}")

Output:

Enter a number: 12345
Sum of digits of 12345 is 15

This digit-extraction pattern shows up in many interview problems — practice it further with our daily Problem of the Day.