Python Program to Find the Sum of Digits in a Number without Recursion

PythonServer Side ProgrammingProgramming

When it is required to find the sum of digits in a number without using the method of recursion, the ‘%’ operator, the ‘+’ operator and the ‘//’ operator can be used.

Below is a demonstration for the same −


 Live Demo

def sum_of_digits(my_num):
   sum_val = 0
   while (my_num != 0):
      sum_val = sum_val + (my_num % 10)
      my_num = my_num//10
   return sum_val
my_num = 12345671
print("The number is : ")
print("The method to calculate sum of digits is being called...")
print("The sum of " +str(my_num) + " is : ")


The number is :
The method to calculate sum of digits is being called...
The sum of 12345671 is :


  • A method named ‘sum_of_digits’ is defined, that takes a number as parameter.
  • A sum is initially assigned to 0.
  • The number is divided by 10 and the remainder obtained is added to the sum.
  • The number is again floor divided by 10 and assigned to the number itself.
  • The sum value is returned as output from the function.
  • A number is defined, and is displayed on the console.
  • The method is called by passing this number as a parameter.
  • The output id displayed on the console.
Published on 12-Mar-2021 12:03:46