Python Program to Add all the digits of given number

In this tutorial, we are going to learn how to add all digits of given number in Python. So let’s get started.

Adding all digits of a number in Python

To add all digits of given number a given number we need to follow some steps.

Steps to follow:

  1.  User has to enter a value.
  2. Using a loop, we will get each digit of the number by taking modulus to the number.
  3. Add the digits to some variable.
  4. Divide the number with 10 to remove the last digit.
  5.  Print the sum.

In this program, we create a function named reverse. The reverse function takes a number as an argument and returns the reversed number.

def reverse(number): 
  y=0 
  while(number>=1):
   z = number % 10
   y = y + z
   number = number / 10
   number = int(number)
  return y

Explanation :




The last digit of the number can be obtained by using a modulus operator. In the above program, we used while loop to get each digit. The last digit is added to variable y in the above program.

Divide the number with 10 to remove the last digit in the given number. This loop terminates when the value of the number is 0 and returns variable y to main program.

Final code:

def reverse(number):
  y=0
  while(number>=1):
   z = number % 10
   y = y + z
   number = number / 10
   number = int(number)
  return y
Number=int(input("Enter a number: "))
reverse_number=reverse(Number)
print("sum of the digits of the number ",Number," is ",reverse_number)

output:

Enter a number: 56

sum of the digits of the number 56 is 11

So Guy’s, I hope you really enjoy this tutorial and feel free to leave a comment if you have any doubt.

you may also learn:


Leave a Reply

Your email address will not be published. Required fields are marked *