Javaexercise.com

Python Program to Find Sum of Digits

This article is about finding the sum of digits of a number in Python. There can be many ways to find the sum of digits but here we will see some most popular and efficient ways. We used modulo and division operators into while loop and for loops.  Let's see some examples.

Algorithm To Find Sum of Digit in Python

Step 1: Take a number

Step 2: Create a variable sum and initialize with zero

Step 3: Start a loop 

Step 4: Find the sum using modulo and division operator 

Step 5: Repeat step3 until the number becomes zero

Step 6: Display the sum

 

Python Program to Find Sum of Digit in Python

This is the simplest and easy way to find the sum of digits in Python. We just used the modulo and division operators into the while loop and collect sum into a variable. After finishing the loop, the sum is displayed. 

# Take a number
num = 12345
# Set sum zero
sum = 0
print(num)
# Find sum of digits
while num:
  sum += num % 10
  num //= 10
# display sum
print(sum)

Output

12345
15

 

Python Program to Find Sum of Digit

This is another approach that is quite a similar but concise way to get the sum of digits of a number in Python. Here, we combined two statements into a single one which is a feature of Python. See the code and output.

# Take a number
num = 12345
# Set sum zero
sum = 0
print(num)
# Find sum of digits
while num:
  sum, num = sum + num % 10, num // 10
# display sum
print(sum)

Output

12345
15

 

Python Program to Find Sum of Digit using int() function

If you want to use for loop then use the given code. Here, we converted integer values into a string and iterate them using for loop. Inside the for loop, we converted each value into int and get the sum of all the digits. See the code and output.

# Take a number
num = 12345
# Set sum zero
sum = 0
# convert int to string
num_str = str(num)
print(num)
# Find sum of digits
for i in range(0, len(num_str)):
  sum += int(num_str[i])
# display sum
print(sum)

Output

12345
15