Table of contents
1.
Introduction 
2.
Python Program for Sum the Digits of a Given Number
3.
Approach to get the sum of digits in Python
3.1.
1. Using sum() 
3.1.1.
Implementation
3.2.
Python
3.3.
2. Using int() and str()
3.3.1.
Steps of Approach
3.3.2.
Implementation
3.4.
Python
3.5.
3. Using sum(), map() and strip() methods
3.5.1.
Steps of Approach
3.5.2.
Implementation
3.6.
Python
3.7.
4. Using Iteration
3.7.1.
Steps of Approach
3.7.2.
Implementation
3.8.
Python
3.9.
5. Using Recursion
3.9.1.
Steps of Approach
3.9.2.
Implementation
3.10.
Python
4.
Frequently Asked Questions
4.1.
How do you print the sum of two digits in Python?
4.2.
How do you find the sum of numbers in Python?
4.3.
How do you sum the digits of a number in Python Class 11?
4.4.
How do you find the sum of 4 digits in Python?
5.
Conclusion
Last Updated: Oct 8, 2024
Medium

Sum of Digits of a Number in Python

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

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.

Sum of Digits in Python

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.

  1. Using Sum()
  2. Using int() and str()
  3. Using sum(), map() and Strip()
  4. Using Iteration
  5. 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
Run Code

Output:

Enter the value:674

The output will be: 17


Explanation:

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
Run Code

 

Output:

The output will be: 15
The output will be: 21


Explanation:

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.
     

Implementation

  • Python

Python

def Total(n):
string = str(n)
list_num = list(map(int, string.strip()))
return sum(list_num)

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
Run Code

Output:

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.

Using Iteration

To get all the digits.

Using Iteration approach

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
Run Code

Output:

The output will be: 16


Explanation:

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
Run Code

Output:

Enter the value: 654
15

You can practice by yourself with the help of online python compiler.


Explanation:

We have taken user input for this example, for which the value is 654 in our case, and the output for this is 15(6 + 5 + 4).

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

Note: In terms of speed, Recursion execution is slower than loops.

We have seen different approaches to solving the problem of the sum of digits in Python. Let’s move to the faqs section.

Also read palindrome number in python.

Frequently Asked Questions

How do you print the sum of two digits in Python?

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.

Refer to more articles like this.

  1. Basics of Python
  2. Fibonacci Series in Python
  3. Floor Division in Python
  4. Python Square Root
  5. Python String Concatenation
     

Refer to our Guided Path to upskill yourself! also, check out the mock test series and participate in the contests hosted on Code 360

Live masterclass