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.
And the sum is 15.
We will discuss three ways to write the python program for it.
- By using the while loop.
- By taking the number as a string.
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# taking number num = int(input("Enter a number: ")) # initializing sum to zero sum = 0 # going through every digit using every for loop while num > 0: d = num%10 num = num//10 sum += d # we can write above code in single line # uncomment the below line and comment the above three lines # num,sum = num//10,sum+(num%10) # printing the sum print("The sum of digits of number is",sum) |
1 2 3 4 |
Enter a number: 568745 The sum of digits of number is 35 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
# taking number as string num = input("Enter a number: ") # initializing sum to zero sum = 0 # going through every digit using every for loop for i in num: sum += int(i) # printing the sum print("The sum of digits of number is",sum) |
Output:
1 2 3 4 |
Enter a number: 1684667 The sum of digits of number is 38 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# defining getDigitSum() function def getDigitSum(num): if num == 0: return num else: return num%10 + getDigitSum(num//10) # taking number num = int(input("Enter a number: ")) # initializing sum to the return value of getDigitSum() function sum = getDigitSum(num) # printing the sum print("The sum of digits of number is",sum) |
Output:
1 2 3 4 |
Enter a number: 532466 The sum of digits of number is 26 |