# Python Program – Sum of Squares of First N Natural Numbers

## Sum of Squares of First N Natural Numbers

To find the sum of squares of first N natural numbers, read the value of N from user using input(), then iterate from 1 to N using a For Loop, find square of each number and accumulate it in sum over the iterations.

The sum of squares of first N natural numbers is

``sum = 12 + 22 + 32 + . . . + n2``

If you are good in remembering formula or remembering that there is a formula, then the following will help you in finding the sum of squares of first n natural numbers.

``n (n + 1) (2n + 1) / 6``

We shall go through two of these methods to find the sum of squares of first n natural numbers using Python.

## Program using For Loop

In the following program, we shall define a function sumOfSquares() that takes n as argument, use For Loop to compute the sum of squares, and then return the sum.

We read n from user, call sumOfSquares() with the n passed as argument.

Input

n, where n > 0

Python Program

``````def sumOfSquares(n) :
if n < 0:
return
sum = 0
for i in range(n+1):
sum += i*i
return sum

n = int(input('Enter n : '))
sum = sumOfSquares(n)
print(f'Sum : {sum}')``````
Copy

Output

``````Enter n : 6
Sum : 91``````

Important Points regarding above program

• input() function reads a string from standard input. Therefore, we have used int() function to convert string to integer.
• If given n is less than zero, we are returning nothing.
• We used range(1, n+1) to iterate from 1 to n.
• += is Addition Assignment Operator.

## Program using Formula

In the following program, we shall define a function sumOfSquares() that takes n as argument, uses the following formula to compute the sum of squares, and then return the sum.

``n (n + 1) (2n + 1) / 6``

We read n from user, call sumOfSquares() with the n passed as argument.

Input

n, where n > 0

Python Program

``````def sumOfSquares(n) :
if n < 0:
return
sum = n * (n + 1) * (2 * n + 1) / 6
return int(sum)

n = int(input('Enter n : '))
sum = sumOfSquares(n)
print(f'Sum : {sum}')``````
Copy

Output

``````Enter n : 6
Sum : 91``````

Since we have division operation in the formula, Python implicitly typecasts the value to floating-point number. We may convert the float to int using int() function.

Code copied to clipboard successfully 👍