Find the Sum of Digits of a Number in Python using For Loop

In this Python Blog, I will explain how to find the sum of digits of a number in Python using for loop. In the process, I will use different methods present in Python with the for loop to find the sum of the digits of a number. Also, I will explain how to find the sum of digits of a number in Python without loop.

I will explain each method with the help of some demonstrative examples.

Python, with its rich standard library and straightforward syntax, provides multiple ways to achieve a task. One such common task is to find the sum of the digits of a number. In this article, we will explore different methods to calculate the sum of digits of a number using a for loop in Python.

For loop in Python

In Python, the for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) or other iterable objects. To know more about for loop in Python, you can refer to our article: for loop in Python.

Methods to find the sum of digits of a number in Python using for loop

There are many different methods in Python to find the sum of digits of a number using a for loop.

  • The str() with int() function
  • Using iteration
  • Using the sum() function
  • The += operator

Let’s see them one by one using some illustrative examples:

Method 1: Sum of digits in Python without function using str() with int() function in for loop

In Python, the int() method is used to convert the string value into an integer, and the str() method is used to convert the integer number to a string.

Example: Let’s take an example and check how to find the Sum of digits of a number in Python using str() and int() in a for loop in Python.

USA_state_ZIPCode = 76450
total=0
for i in str(USA_state_ZIPCode):
    total=total+int(i)
print("Sum of digits of a number :",total)

Output: In the given code first, we are initializing a Python variable with 0 so that we can store the sum of the digits of a number in it. Next, we converted the number to a string by using the str() method. After that, we used the for loop to iterate each digit of a number and convert them into an integer by using the int() method.

Sum of digits of a number : 22
sum of digits of a number in python using for loop

This way we can use the str() and int() functions to find the sum of digits of a number in Python using for loop.

Method 2: Sum of digits in Python using iteration

To calculate the sum in this method, use a loop to repeatedly extract the last digit from the number and accumulate the sum.

In this case, We begin by initializing a total sum to zero and taking the absolute value of the number in Python. Then, using a loop, the method repeatedly:

  • Extract the last digit from the number.
  • Adds this digit to the total sum.
  • Removes the last digit from the number.

This loop continues until there are no more digits left in the number, after which the accumulated total is returned.

Example: Let’s take an example and check how to find the Sum of digits of a number in Python using iteration.

def sum_of_digits_iteration(n):
    n = abs(n)
    total = 0
    while n:
        total += n % 10
        n //= 10
    return total

number = 89589
print("Sum of the digits is:", sum_of_digits_iteration(number))

Output: In this method, we will divide a number by 10 to get the rightmost digit, which is 0, by the number. The rightmost digit will eventually make up the remainder. Use the remaining operator “%” to obtain the remainder. Divide the quotient by 10 to get a number’s entire digit count. Use “//” to obtain an integer quotient each time.

Sum of the digits is: 39
sum of digits python

This way we use iteration to find the sum of digits of a number in Python using a while loop.

Method 3: Sum of digits of a number Python using sum() function

Python’s sum() function is used to calculate a number’s digit sum in a list. This approach combines string conversion and list comprehension to extract digits and then uses the sum() function to compute their total through Python.

Example: Here we will take an example and check how to find the sum of digits of a number in Python using the sum() function.

def sum_of_digits_sum(n):
    return sum([int(digit) for digit in str(abs(n))])

number = 79038
print("sum of the digits is:", sum_of_digits_sum(number))

Output: Using a list comprehension, the number (now a string) is processed digit by digit. Each character (digit) is converted to its integer form. This results in a list of integers. The built-in sum() function is used to calculate the total sum of the integers in the list.

sum of the digits is: 27
sum of digits using for loop in python

This method offers a compact and Pythonic way to sum of digits of a number in Python using for loop, leveraging list comprehension and built-in functions like sum().

Method 4: Sum of digits in Python using for loop with += operator

The += operator is referred to as an “in-place addition” operator or an “augmented assignment” operator. It provides a concise way to update the value of a variable by adding another value to it.

Example: We can compute the sum of digits of a number in Python using for loop with the += operator in the following manner:

def total_runs_scored(num):
    total_runs = 0
    num_str = str(num)
    for inning in num_str:
        total_runs += int(inning)
    return total_runs

runs_in_each_inning = 12345
print(f"Total runs scored in the game: {total_runs_scored(runs_in_each_inning)}")

Output: The += operator is used to add the number of runs from each iteration to the variable, thus calculating the total of all digits through Python.

Total runs scored in the game: 15
sum of digits of a number in python using function

This way we can use the += operator to find the sum of digits of a number in Python using for loop.

Methods to find the sum of digits of a number in Python without loop

There is one way to find the sum of digits of a number in Python without loop:

Method: Sum of digits of a number in Python using recursion in for loop

Recursion is a programming technique where a function calls itself in order to solve a larger problem by solving smaller instances of the same problem.

If we want to find the sum of digits of a number in Python, one approach could be to isolate the last digit and then add it to the sum of the remaining digits. This pattern can repeat until there are no digits left, which is the base case that stops the recursion.

Example: For our purposes, let’s assume we have been tasked to analyze the sum of digits of various numbers for a study through Python but couldn’t use loops.

def sum_of_digits(n):
    if n == 0:
        return 0
    else:
        return n % 10 + sum_of_digits(n // 10)

ssn = "123-45-6789"
ssn_clean = int(ssn.replace("-", ""))
print("Sum of digits of a number is:", sum_of_digits(ssn_clean))

Output: Though our string contains some other characters than numbers, we are using the replace() method to replace them with an empty string. and after that convert them into an integer and then apply the recursion function on it.

Sum of digits of a number is: 45
calculate sum of digits of a number in python

This way we can use a recursive function in Python to find the sum of digits of a number in Python without loop.

Conclusion

In this article, we have discussed How to find the Sum of digits of a number in Python using for loop and also we have covered the sum of digits of a number in Python without loop with the help of many different methods like the str() and int() functions, iteration with while loop, using sum() function, the += operator, or recursion function.

We have also seen some demonstrative examples related to all the methods mentioned above. Now, the choice totally depends on the coder to select their method in respective of their problems or requirements.

Also, take a look at some more Python tutorials.