Find Sum of Squares of Digits of a Number in Python

I was working on a Python project where I had to calculate the sum of squares of digits of a number. It sounded simple, but I wanted to explore different ways to do it efficiently.

As a Python developer with my experience, I’ve learned that there’s always more than one way to solve a problem in Python. In this tutorial, I’ll show you multiple methods to find the sum of squares of digits of a number, from using a basic while loop to more Pythonic approaches like list comprehension and recursion.

By the end of this article, you’ll not only understand how to calculate it but also learn how to choose the best method based on your use case.

What is the Sum of Squares of Digits?

Before we jump into the code, let’s quickly understand what we’re trying to achieve. The sum of squares of digits means taking each digit of a number, squaring it, and then adding all those squares together.

For example, if the number is 123, then the sum of squares of its digits is: 1² + 2² + 3² = 1 + 4 + 9 = 14

This is a common operation in mathematical and algorithmic problems, especially in data analysis, number theory, and machine learning preprocessing.

Method 1 – Use a While Loop in Python

When I first started coding in Python, the while loop was my go-to approach for problems like this. It’s simple, clear, and easy to debug.

Here’s how you can find the sum of squares of digits using a while loop:

def sum_of_squares_while(num):
    total = 0
    while num > 0:
        digit = num % 10
        total += digit ** 2
        num //= 10
    return total

# Example usage
number = 123
result = sum_of_squares_while(number)
print(f"The sum of squares of digits of {number} is {result}")

This code works by repeatedly extracting the last digit using the modulus operator (% 10), squaring it, and adding it to the total. Then, it removes the last digit using integer division (// 10).

The sum of squares of digits of 123 is 14

You can refer to the screenshot below to see the output.

sum of digits

This method is efficient and works perfectly even for large numbers.

Method 2 – Use a For Loop and String Conversion

Sometimes, I prefer converting the number into a string because it allows me to iterate over each digit easily. This approach feels more Pythonic and readable.

Here’s how it looks:

def sum_of_squares_for(num):
    total = 0
    for digit in str(num):
        total += int(digit) ** 2
    return total

# Example usage
number = 987
result = sum_of_squares_for(number)
print(f"The sum of squares of digits of {number} is {result}")

You can refer to the screenshot below to see the output.

sum of squares python

In this method, I convert the number to a string so that I can loop through each character. I then convert each character back to an integer before squaring it.

Method 3 – Use List Comprehension in Python

As I became more comfortable with Python, I started using list comprehensions for concise and elegant solutions. They make your code shorter and often more efficient.

def sum_of_squares_listcomp(num):
    return sum(int(digit) ** 2 for digit in str(num))

# Example usage
number = 456
result = sum_of_squares_listcomp(number)
print(f"The sum of squares of digits of {number} is {result}")

You can refer to the screenshot below to see the output.

find the sum example

This one-liner uses Python’s built-in sum() function and a generator expression to compute the result in a single line.

Method 4 – Use Recursion in Python

Recursion is another elegant way to solve this problem. It’s a bit advanced, but a great way to understand how Python handles function calls.

Here’s how you can do it:

def sum_of_squares_recursive(num):
    if num == 0:
        return 0
    else:
        digit = num % 10
        return (digit ** 2) + sum_of_squares_recursive(num // 10)

# Example usage
number = 789
result = sum_of_squares_recursive(number)
print(f"The sum of squares of digits of {number} is {result}")

You can refer to the screenshot below to see the output.

sum of square numbers

In this recursive approach, the function keeps calling itself with a smaller number (num // 10) until it reaches zero. Each call contributes the square of the last digit to the total sum.

Method 5 – Use Python’s Map and Lambda Functions

If you enjoy writing compact, functional-style Python code, this method is for you. It combines the power of map() and lambda to achieve the same goal.

Here’s the code:

def sum_of_squares_lambda(num):
    return sum(map(lambda x: int(x) ** 2, str(num)))

# Example usage
number = 321
result = sum_of_squares_lambda(number)
print(f"The sum of squares of digits of {number} is {result}")

This method is concise and expressive. It’s also a great way to demonstrate functional programming concepts in Python.

Method 6 – Use NumPy (for Large Data Sets)

If you’re working with large numerical datasets or arrays, using NumPy can significantly improve performance. NumPy operations are vectorized and optimized for speed.

Here’s an example:

import numpy as np

def sum_of_squares_numpy(num):
    digits = np.array(list(str(num)), dtype=int)
    return np.sum(digits ** 2)

# Example usage
number = 654
result = sum_of_squares_numpy(number)
print(f"The sum of squares of digits of {number} is {result}")

This approach is particularly useful when you want to apply the same logic to a list or array of numbers efficiently.

Real-World Example: Check for Happy Numbers

You might be wondering, where is this concept used in real life? One interesting use case is in detecting Happy Numbers. A happy number is one where repeatedly replacing the number with the sum of the squares of its digits eventually leads to 1.

Here’s a quick example:

def is_happy_number(num):
    seen = set()
    while num != 1 and num not in seen:
        seen.add(num)
        num = sum(int(digit) ** 2 for digit in str(num))
    return num == 1

number = 19
if is_happy_number(number):
    print(f"{number} is a Happy Number!")
else:
    print(f"{number} is not a Happy Number.")

This is a fun and practical way to apply the concept of the sum of squares of digits in Python.

Common Mistakes to Avoid

  • Forgetting to convert characters to integers: When looping through a string, always use int(digit) before squaring.
  • Using floating-point division (/) instead of integer division (//): This can cause unexpected results.
  • Not handling negative numbers: You can use abs(num) to handle them safely.

In this tutorial, I showed you six different Python methods to find the sum of squares of digits of a number, from basic loops to advanced NumPy operations.

Each method has its own advantages:

  • The while loop is simple and efficient.
  • The for loop and list comprehension are more Pythonic.
  • The recursive approach helps understand function calls.
  • The lambda and NumPy methods are great for compact and large-scale computations.

You can read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.