Calculate Sum Get User Input Patterns Program Find Area of CircleFind Area of Rectangle Perimeter of Rectangle Find Even and Odd Numbers Find Sum of Digit in Python Find Factorial in PythonPrint Fibonacci Series Check Armstrong Number Reverse a Number Check Palindrome Number Swap Two Numbers Matrix MultiplicationFind Perfect NumberAdd Two Matrix in Python Find Sum of Squares Find Sum of Cubes Find URL in String
Find Largest in List Find Duplicate in List Check Alphabet Remove Duplicate Elements from List Reverse List Elements Find Element in Python List Interchange first and last element in List Find Even Numbers in List Find Length of a List Find Sum of list Elements Find Elements in List Get the product of List elements Interchange List Elements Find Smallest Elements in List Find Max Value in a List
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.
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
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