Python Program to Find the Sum of Digits of a Number – Programming Code Examples
Python

Python Program to Find the Sum of Digits of a Number2 min read

Write a program to find the sum of first and last digits of a given number in python

In this post, we will discuss how to write a python program to find the sum of digits of a number.

In this python program, we will simply add the digits present in a number.

For example –
The number is 15423.
And the sum is 15.




We will discuss three ways to write the python program for it.

  1. By using the while loop.
  2. By taking the number as a string.
  3. And by using recursion.

Let’s discuss these ways one by one.

Python Program to Find the Sum of Digits of a Number using While loop

In this method, we use the while loop to get the sum of digits of the number.

Here, we take the remainder of the number by dividing it by 10 then change the number to the number with removing the digit present at the unit place. We repeat this process in the while loop. And in every iteration, we sum up the remainder till the number becomes 0.

Let’s see the code.

We can decrease the number of code lines by replacing the statements present in the body of while loop with just one statement.
Look in the code I have put the one line statement code in the comment.

Python Program to Find the Sum of Digits of a Number by taking Number as a String

In this, we will take the number as a string and then by using for loop we traverse through every digit and add it up to the sum.

Output:

Python Program to Find the Sum of Digits of a Number using Recursion

In this, we will define a recursive function getDigitSum(). This function will return the sum of the digits.

Output:

 

Leave a Comment