In Python, finding the sum of digits of a number is a common programming task. It involves breaking down a number into individual digits and adding them together to calculate the total sum. This can be achieved with the help of different approaches, like converting the number to a string and iterating over its characters, or using mathematical operations like modulo and division to extract the digits.

In this article, we will discuss these methods in detail. We will implement them with proper examples and code, to make you understand clearly.

Python is an easy-to-write general-purpose programming language for programmers. It is simple, has numerous applications, and is widely used in the Artificial Intelligence domain.

Python Program for Sum the Digits of a Given Number

Problem Statement: We will be given a number as input to calculate the sum of the digits in that number using Python. Now how to find the total sum using the digits of a number. Letâ€™s go through these examples below.

Example 1

Input: 423

Output: 9

Explanation: 4 + 2 + 3 = 9

Example 2

Input: 674

Output: 17

Explanation: 6 + 7 + 4 = 17

Before stepping into the solution, try finding the sum of digits of a number yourself on the Coding Ninjas Studio platform.

Letâ€™s move on to different approaches to get the sum of digits in Python.

Approach to get the sum of digits in Python

We will be going through five approaches to get the digit sum in Python.

Using Sum()

Using int() and str()

Using sum(), map() and Strip()

Using Iteration

Using Recursion

1. Using sum()

The program takes in a number as input, and we will calculate the total sum of digits in Python using the sum() function. The sum() function is an inbuilt python function to sum the integers.

Implementation

Python

Python

# Python program n = int(input("Enter the value: ")) result = sum(int(digit) for digit in str(n)) print("The output will be: ",result)

You can also try this code with Online Python Compiler

In the above-tested example, we are using the sum() in-built function to get the sum of the individual digits in Python.

The user input for this example is 674, and the output will be 17 because 6 + 7 + 4 = 17.

Time Complexity: O(n), where n is the number of digits in input.

2. Using int() and str()

We will use the int() and str() methods in this approach to get the sum.

Steps of Approach

Here the str() function converts the input to string(an iterable object).

The for loop is initialized for every digit in the input string.

The digit is converted to an integer using the int() in-built function and added to the sum variable.

Call out our â€˜Totalâ€™ function and print the sum.

Implementation

Python

Python

# Implementation of program to get the sum of digits in Python def Total(n): try: total = sum(int(digit) for digit in str(n)) return total except ValueError: return "Invalid input. Please enter a valid integer."

n = 456 print("The output will be:", Total(n)) n = 786 print("The output will be:", Total(n))

You can also try this code with Online Python Compiler

In the above example, we use the str() function to convert the input number into a string and the int() inbuilt method to convert the digit to an integer.

Time Complexity: O(n), where n is the number of digits in input.

3. Using sum(), map() and strip() methods

In this approach, we will use three methods to compute the sum of digits in Python.

The sum() method is used to find the sum of numbers.

The map() function is used to convert the number in the list.

The strip() function in Python is an interesting method to get the exact string after removing the white spaces from both the left and right side of the string.

Steps of Approach

First, create a function, let's say, â€˜Totalâ€™ with a parameter n.

Then the number n is converted to string using the str() in-built function.

After the conversion of the number to a string, the string is stripped using the strip() function.

After stripping the string, the map() method is used to convert it to the list.

The sum() method is a useful function to sum up the digits available and get the total sum of it.

n = 234 print("The output for n =", n, "is:", Total(n))

# Taking user input and validating it as an integer while True: try: s = int(input("Enter the Value: ")) print("The output for s =", s, "is:", Total(s)) break # Break out of the loop if input is successfully converted to an integer except ValueError: print("Invalid input. Please enter a valid integer.")

You can also try this code with Online Python Compiler

The output will be: 9
Enter the Value: 784
The output will be: 19

Explanation:

The first input is 234, and the output will be 9, where 2 + 3 + 4 will give us the result as 9. And for the second value, we have taken the input from the user, which is 784 in our case, and it gives the result as 19(7 + 8 + 4).

Time Complexity: O(log n), where n is the number of digits in input.

4. Using Iteration

In this approach, we will use an iteration method to calculate the sum of digits using loops. Loops help us get the particular statement as often as we want.

As we all know, dividing a number by 10 gives us the remainder as the rightmost digit. And to get all the digits of a number, we divide the quotient by 10.

Letâ€™s see what operators we use for this.

To get all the digits.

Steps of Approach

We will declare a function called total that will have a parameter of n.

A variable sum is declared to store the sum of digits and a while that will run till n!=0.

Add the value; remainder returned by n%10 to the sum variable.

Change n to n//10.

Call out the function and print the total sum.

Implementation

Python

Python

def Total(n): sum = 0 while (n != 0): sum = sum + (n % 10) n = n // 10 return sum

n = 3391 print("The output will be:", Total(n))

You can also try this code with Online Python Compiler

We have taken input as 3391, for which our output is 16 as 3 + 3 + 9 + 1 using a while loop.

Time Complexity: O(logn), n is the given input.

5. Using Recursion

In this approach, we will execute the above method using Recursion. Recursion is a method or a technique of calling a function from itself until a specified condition is met(Base Condition).

Steps of Approach

Create a function Total with a parameter n.

Define a base condition that, if n==0, returns 0. Else, call the Total function recursively using different parameters.

Pass n/10 as a parameter and add the remainder (n%10) and the value returned by the function.

Call out for our function Total and print the sum.

Implementation

Python

Python

def Total(n): if n == 0: return 0 return int(n % 10) + Total(int(n // 10))

# Taking the user input s = int(input("Enter the value: ")) result = Total(s) print("Sum of the digits:", result) # Taking the user input s = int(input("Enter the value: "))

You can also try this code with Online Python Compiler

To use the input() function to get user input, convert it to integers, add them, and then print the result using print() it helps to print the sum of two digits in Python.

How do you find the sum of numbers in Python?

To find the sum of numbers in Python, use the built-in sum() function, providing a list or iterable of numbers.

How do you sum the digits of a number in Python Class 11?

For summing the digits of a number in Python (Class 11), convert the number to a string, iterate through its characters, and sum the converted digits.

How do you find the sum of 4 digits in Python?

To find the sum of 4 digits in Python, obtain the individual digits and use the sum() function. For example, if the digits are stored in a list, apply sum(list_of_digits).

Conclusion

In this article, we talked about how to find the sum of digits of a number in Python. We learned that you can break a number into its separate digits and then add them up to get the total sum. You can do this by turning the number into a string and going through each character, or by using math operations to get each digit one by one.