Python | Find Sum of Digit of a Number Without Recursion

Let us rub our hands on this problem by taking a look at various methods.

Method 1: Using for loop

def perform_sum(n):
    
    sum = 0
    for digit in str(n): 
      sum += int(digit)      
    return sum
   
n = input("Enter the number whose sum of digits you want to find: ")
print("The sum of digits in your number is: ",perform_sum(n))

Output:

Enter the number whose sum of digits you want to find: 369
The sum of the digits in your number is: 18

Explanation

Here we simply passed the number entered by the user to a function. There we run the for loop through the entered number. However, we converted the number to string format. Now we add the visited element in the variable named sum and add the previously stored value to the newly added one.

Method 2: Using modulo and floor division

def perform_sum(n):
    
    sum = 0
    while (n != 0):
       
        sum = sum + (n % 10)
        n = n//10
       
    return sum
   
n = 369
print("Here is the sum of digits in the number entered bu user: ",perform_sum(n))

Explanation

We checked the value of n using a while loop. If the value is not equal to zero then only the code flow enters into the loop. Using the % we perform n%10 and then add it to the sum variable. After that, we perform floor division of n. This while loop goes on till the value of n is equal to zero.

Method 3: Using sum()

def perform_sum(n):
    
    strr = str(n)
    list_of_number = list(map(int, strr.strip()))
    return sum(list_of_number)
   
n = input("Enter the number whose sum of digts you want:")
print("Here is the sum of digits in the number entered bu user: ",perform_sum(n))

Explanation:

We took the input from the user as a string. We then converted the string format to int using the map function. Map function simply takes the function and is iterable. When a function is applied to each item in an iterable (list, tuple, etc.), the map() method produces a map object, which is an iterator, with the results. With that, we finally convert the output of the map function to a list. Now simply using the sum() function we passed on the list to this function.

Here is the end of our article. We hope this article helped you in learning new techniques to solve problems in Python.

Share:

Author: Dhvanil V