Python Program to Find Sum of Squares of N Numbers in Python

To find the sum of squares of n numbers in Python, we are providing some solutions here. In this article, we will learn to create Python programs that will return the sum of squares of the n numbers. Numbers can be any integer that will be taken by a user during program execution. We will create the two programs:

• By using loop

• By using a mathematical expression

Let's get started.

Python Program to print sum of squares of n Number

In this program, we first take user input and then start a loop that calculates the sum of squares till the specified condition. After that, we print the result. See the Python code.

``````# Python program to find the sum of the square of n numbers
# Take user input
n = int(input("Enter Number: "))

sum = 0
for i in range(n+1):
sum += i**2

# Print Result
print("Sum of squares of first {} natural numbers: ".format(n), sum)
``````

Output:

Enter Number:  2
Sum of squares of first 2 natural numbers:  5

Python Program to print sum of squares using math expression

Here, we are using a mathematical expression that returns the sum of all the n numbers. It is the simplest and one-line solution that does not require any loop as we used in the above program. See the output of the Python code.

``````# Python program to find the sum of the squares of n numbers
# Take user input
n = int(input("Enter Number: "))

sum = 0
for i in range(n+1):
sum = (n * (n + 1) * (2 * n + 1)) // 6

# Print Result
print("Sum of squares of first {} natural numbers: ".format(n), sum)``````

Output:

Enter Number:  2
Sum of squares of first 2 natural numbers:  5

Trending