Sum of digits of a number in Python

This gone be our second program in Python.We shall learn to write program to print the sum of digits of a given number.We have already seen the same program in C,C++,Java.Today we shall do the same in python.

We all know the main concept involved in finding sum of digits.First we need to separate each digit from the given number.And then we need to add them all to calculate the sum of digits.To separate a digit from the given number we use the modulus operator (%).Because if any number is divide by 10 we get the last digit of the number as remainder.So that we can get all the digits present in the number.Now we shall write the code and test it.

n = input("\nEnter any number to find the sum of digits of it:")  #To get the input from the user.
temp = n = int(n) #String to int
remainder = sum = 0 #Initialization of remainder and sum.
while (  temp > 0) :
	remainder = temp % 10
	temp = temp/10
	sum = sum +remainder
print ("\nSum of digits of  %d %d" % (n,sum))

The default datatype for a variable assigned by input statement is String.Since we are going to use that number in while we need to typecast it to int.
Output:
sum of digits

Download the source code

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Python and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s