Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconPython Program for Sum of Digits

Python Program for Sum of Digits

Last updated:
15th Jun, 2023
Views
Read Time
5 Mins
share image icon
In this article
Chevron in toc
View All
Python Program for Sum of Digits

Python- an overview

Python is the most sought-after programming language because of various reasons. The few features of Python that have made it more popular are:

  • Python can operate on any platform like Windows, Linux, Mac, Raspberry Pi etc.
  • The syntax of Python is simple and the code is easily readable as it is analogous to the English Language.
  • Developers can efficiently write codes with a fewer number of lines with the syntax offered by Python.
  • It offers quick prototyping as it runs on an interpreter system.
  • Python can be used for procedural, functional and object-oriented programming language.

Basics of Digit Sum

The digit sum of any number refers to the result obtained by adding all the digits of the number. The addition of digits is repeated till a single digit sum is obtained. In other words, the addition of digits is repeated if the sum obtained by adding the digits of a number is more than the digit 9. A digit sum is also referred to as a reduced digit sum in some cases. The digit sum is the final result of the repeated addition of digits until a unit digit sum is obtained. In Mathematics, the digit sum of a number is denoted as Digit Sum (n) where ‘n’ denotes the number whose digit sum is to be computed.

Let us consider an example to understand the concept of finding the digit sum. If the digit sum of the number ‘231’ is to be determined, the individual digits are added till the sum obtained is a single digit. 

Digit Sum (123) = 1 + 2 + 3 = 6

Let us take another example to understand the concept better. Let’s find the digit sum of the number ‘987’.

Digit Sum (987) is calculated as follows:

= 9 + 8 + 7 = 24

= 2 + 4 = 6.

So, the digit sum of 987 is 6.

Check Out upGrad’s Data Science Courses 

Sum of digits in Python

Python offers a good platform for developing a code to find the sum of digits of a number which forms a basis for determining the digit sum of any input number. The general algorithm that is used in Python to develop a code for finding the sum of digits in a specified number is as follows. 

Step 1: Read the input number.

Step 2: Declaration of a variable that can store the sum and initialization of the variable that indicates the sum as ‘0’.

Step 3: Use a conditional loop to repeat step 4 and step 5 till the number becomes zero.

Step 4: Extract the number’s rightmost digit using the remainder operator (%). The obtained digit is to be added to the variable reflecting the sum.

Step 5: The number is divided by 10 and the rightmost digit is removed.

Step 6: The result stored in the variable declared for ‘sum’ is printed.

There are several methods in Python that can be implemented to find the sum of digits of a number. Let’s discuss these methods in subsequent sections.

Explore our Popular Data Science Courses

Method 1: Use str() and int() methods to determine the sum of digits in Python

The str() method converts the input number into a string and the int() method converts the digits of the string into an integer. In this method, the number whose sum of the digits is to be determined is converted into a string. Each digit of the string is iterated. During each iteration, a string digit is converted into an integer and added to the sum.

Top Data Science Skills to Learn

Method 2: Use of sum() methods to find the sum of digits in Python

The sum() method determines the sum of elements of a list in Python. Here, the number is transformed into a string using the str() method. The string is stripped and converted into a list of numbers using the strip() and map() functions, respectively. Finally, the sum() function is used to determine the sum of digits of the number.

 

Read our popular Data Science Articles

Method 3: General Approach to determine the sum of the digits

In this method, the general algorithm discussed in one of the previous sections is implemented as a Python code either by iteration or by recursion. Look at the examples of Python codes shown below that show both iterative and recursive approach to determine the sum of the digits of a number.

Sum Of Digits Using General Approach Code Example:

The most basic approach to estimating the sum of digits of a number in Python is shown below:

sum=0

while(number > 0):

    dig = number % 10

    sum = sum + dig

    number = num//10

print (sum)

For Example,

number: 12345

Output:

15

Sum Of Digits Using str() And int() Code Example

The integer is transformed into a string using the str() technique. The string digit is transformed into an integer using the int() function. The sum of digits Python program for the same is shown below:

def cal_sum (n):

sum = 0

for i in str (n):

sum += int (i)

return sum

n = 12345

print(cal_sum (n))

Output:

15

Sum Of Digits Using sum() Code Example

The sum() adds the start and items of the given iterable from left to right.

  • The syntax of the in-built function sum() is:

sum(iterable, start)

  • sum() Parameters
  1. Iterable: List, tuple, dict, etc. The items should be numbers.
  2. start: this value is added to the sum of items of the iterable.
  • sum() Return Value

sum() returns the sum of the start and items of the given iterable.

The Python program for the same is shown below:

def getSum (num):

stringg = str(num)

list_number = list (map (int, stringg.strip()))

return sum (list_number)

n = 12345

print(getSum (n))

Output:

15

Sum Of Digits Using Recursion Code Example

def sumofDigits (num):

    return 0 if num == 0 else int (num % 10) + sumofDigits(int (num / 10)) 

number = 12345

print(sumofDigits (number))

Practical Applications of finding the number’s sum of digits

  • Finding the sum of digits of a number is an essential element of quick divisibility tests. For example, any natural number is divisible by 3 only if the sum of its digits is divisible by 3.
  • This is a basis for the rule of nines and casting of nines techniques.
  • It is also a crucial constituent of the checksum algorithms.

If you are curious to learn about tableau, data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Explore Free Courses

Suggested Blogs

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905281
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions & Answers [For Freshers & Experienced]
20934
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5068
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5181
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17651
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types & Techniques
10806
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80793
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories & Types [With Examples]
139149
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon