In this article, we will show you, How to write a Python Program to calculate Sum of Series 1²+2²+3²+….+n² using For Loop and Functions with example.
The Mathematical formula for Sum of series 1²+2²+3²+….+n² = ( n (n+1) (2n+1)) / 6
Python Program to calculate Sum of Series 1²+2²+3²+….+n²
This Python program allows user is asked to enter any positive integer. Next, this program will find sum of series 12 + 22 + 32 + … + n2 using the above formula.
# Python Program to calculate Sum of Series 1²+2²+3²+….+n² number = int(input("Please Enter any Positive Number : ")) total = 0 total = (number * (number + 1) * (2 * number + 1)) / 6 print("The Sum of Series upto {0} = {1}".format(number, total))
OUTPUT
ANALYSIS
Sum = (Number * (Number + 1) * (2 * Number + 1 )) / 6
Sum = (6 * (6 + 1) * (2 * 6 +1)) / 6 => (6 * 7 * 13) / 6
Sum = 91
Python Program to calculate Sum of Series 1²+2²+3²+….+n² Example 2
If you want to display the series order 12 + 22 + 32 +42 + 52 , we have to add extra For Loop along with If Else
# Python Program to calculate Sum of Series 1²+2²+3²+….+n² number = int(input("Please Enter any Positive Number : ")) total = 0 total = (number * (number + 1) * (2 * number + 1)) / 6 for i in range(1, number + 1): if(i != number): print("%d^2 + " %i, end = ' ') else: print("{0}^2 = {1}".format(i, total))
OUTPUT
Python Program to calculate Sum of Series 1²+2²+3²+….+n² using Functions
This program is same as above but this time we are defining function to place logic
# Python Program to calculate Sum of Series 1²+2²+3²+….+n² def sum_of_square_series(number): total = 0 total = (number * (number + 1) * (2 * number + 1)) / 6 for i in range(1, number + 1): if(i != number): print("%d^2 + " %i, end = ' ') else: print("{0}^2 = {1}".format(i, total)) num = int(input("Please Enter any Positive Number : ")) sum_of_square_series(num)
OUTPUT
Python Program to calculate Sum of Series 1²+2²+3²+….+n² using Recursion
Here, we are using Recursive function concept
# Python Program to calculate Sum of Series 1²+2²+3²+….+n² def sum_of_square_series(number): if(number == 0): return 0 else: return (number * number) + sum_of_square_series(number - 1) num = int(input("Please Enter any Positive Number : ")) total = sum_of_square_series(num) print("The Sum of Series upto {0} = {1}".format(num, total))
OUTPUT