Calculate Sum Get User Input Patterns Program Find Area of CircleFind Area of Rectangle Perimeter of Rectangle Find Even and Odd Numbers Find Sum of Digit in Python Find Factorial in PythonPrint Fibonacci Series Check Armstrong Number Reverse a Number Check Palindrome Number Swap Two Numbers Matrix MultiplicationFind Perfect NumberAdd Two Matrix in Python Find Sum of Squares Find Sum of Cubes Find URL in String
Find Largest in List Find Duplicate in List Check Alphabet Remove Duplicate Elements from List Reverse List Elements Find Element in Python List Interchange first and last element in List Find Even Numbers in List Find Length of a List Find Sum of list Elements Find Elements in List Get the product of List elements Interchange List Elements Find Smallest Elements in List Find Max Value in a List
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.
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
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
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
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