Home »
Python »
Python Programs
Python program to find sum of all digits of a number
Here, we are going to learn how to find the sum of all digits of a given number in Python programming language.
By IncludeHelp Last updated : January 12, 2024
Problem statement
Write a Python program to find sum of all digits of a number.
Example
Consider the below example with sample inputs and outputs:
Input number:
0
Sum of all digits:
0
Input number:
12345
Sum of all digits:
15
Input number:
5678379
Sum of all digits:
45
Finding sum of all digits of a number
To find the sum of digits of a number, write a recursive function, extract the digits by dividing the numbers by 10 and convert it into int using the int() method and then find the floor division (//) by 10. Add the extracted digits. Repeat these steps till the floor division is not 0.
Python program to find sum of all digits of a number
# Python program to find the
# sum of all digits of a number
# function definition
def sumDigits(num):
if num == 0:
return 0
else:
return num % 10 + sumDigits(int(num / 10))
# main code
x = 0
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()
x = 12345
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()
x = 5678379
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()
Output
The output of the above program is:
Number: 0
Sum of digits: 0
Number: 12345
Sum of digits: 15
Number: 5678379
Sum of digits: 45
To understand the above program, you should have the basic knowledge of the following Python topics:
Python Basic Programs »