Sum of Digits

Compute the sum of digits of an integer using a loop.

BeginnerTopic: Loop Programs
Back

Python Sum of Digits Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to find the sum of digits of a number

num = int(input("Enter an integer: "))

total = 0
temp = abs(num)

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

print("Sum of digits of", num, "is", total)
Output
Enter an integer: 1234
Sum of digits of 1234 is 10

Understanding Sum of Digits

We repeatedly extract the last digit with % 10, add it to a running total, and remove it using integer division // 10.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents