Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
About Python
3.
Python Program for Sum the Digits of a Given Number
3.1.
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.
4.
Example 1
4.1.
Example 2
5.
Approach to get the sum of digits in Python
5.1.
Using sum() 
5.1.1.
Implementation
5.2.
Python
5.3.
Using int() and str()
5.3.1.
Steps of Approach
5.3.2.
Implementation
5.4.
Python
5.5.
Using sum(), map() and strip() methods
5.5.1.
Steps of Approach
5.5.2.
Implementation
5.6.
Python
5.7.
Using Iteration
5.7.1.
Steps of Approach
5.7.2.
Implementation
5.8.
Python
5.9.
Using Recursion
5.9.1.
Steps of Approach
5.9.2.
Implementation
5.10.
Python
6.
Frequently Asked Questions
6.1.
How do you print the sum of two digits in Python?
6.2.
How do you find the sum of numbers in Python?
6.3.
How do you sum the digits of a number in Python Class 11?
6.4.
How do you find the sum of 4 digits in Python?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Sum of Digits of a Number in Python

gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction 

In this article we are going to learn various methods to find the sum of digits in a Python number. These techniques involve adding the individual digits, disregarding their place values.

Let’s begin with the problem statement before reaching out to the solutions.

 

Sum of Digits in Python

 

About 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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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 

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)

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.

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))

 

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.

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.")

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.

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))

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.

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: "))

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

Kudos, Ninjas, you have completed the blog, where we have discussed how to write a program to find the sum of digits in Python using various methods like Recursion, sum(), map(), and strip methods, using loops and int() functions.

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 in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

Happy Learning!

Previous article
Character Class Operations in Python
Next article
Python Program to Check if Two Strings are Anagram
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass