Python Program to Find Sum of Squares of Digits of a Number

This article is created to cover a program in Python that find and prints the sum of squares of digits of a number entered by user. For example, if the number entered by user is 342, then the calculation goes like:

342
= 32 + 42 + 22
= 9 + 16 + 4
= 29

That is, 29 is the output produced by the program given below after providing exactly the same input.

Find Sum of Squares of Digits of a Number

The question is, write a Python program to print the sum of squares of digits of a given number. The program given below is answer to this question:

print("Enter a Number: ")
num = int(input())

sum = 0
while num!=0:
rem = num%10
sqr = rem*rem
sum = sum+sqr
num = int(num/10)

print("\nSum of squares of digits of given number is: ")
print(sum)

The snapshot given below shows the initial output produced by this Python program:

Now supply any number as input say 342 and press ENTER key to find and print sum of squares of digits of this number like shown in the snapshot given below:

Modified Version of Previous Program

This program is created to produce manual error message when user inputs an invalid input. The try-except block is used to do the job like shown in the program and its sample run given below:

print("Enter a Number: ", end="")
try:
num = int(input())
temp = num
sum = 0
while temp!=0:
rem = temp%10
sqr = rem*rem
sum = sum+sqr
temp = int(temp/10)
print("\nSum of squares of digits of", num, "=", sum)

except ValueError:
print("\nInvalid Input!")

Here is its sample run with exactly same input as of previous program's sample run:

And here is another sample run with user input other than an integer value say codescracker:

Python Online Test

« Previous Program Next Program »