Series Summation in Python

Series Summation in Python

  1. Series Summation Using the for Loop in Python
  2. Series Summation Using the sum() Function in Python

This tutorial will discuss the methods to carry out series summation in Python.

Series Summation Using the for Loop in Python

Suppose we want to carry out a series summation like 1+2+3+...+n. We can use the traditional for loop in Python to tackle this problem.

For this specific problem, we must set the range of the for loop to n+1 with the range() function and sum up each value inside the loop.

The range() function takes the 3 parameters: starting position, ending position, and the step. If we don’t specify the starting position, the range() function starts from 0 by default.

If we don’t specify the step parameter, the range() function increments the values by 1. To execute correctly, we only need to set the ending position for the range() function.

The following code snippet demonstrates a working implementation of this solution with the for loop in Python.

sum = 0
n = 5
for x in range(1, n+1):
    sum = sum + x
print(sum)

Output:

15

We initialized a sum variable that would store our result. The variable n is the value we want to execute summation.

Here, the variable x increments from 1 to n in the loop. We keep adding this x into our sum variable until the loop ends and print the result after the loop ends.

Series Summation Using the sum() Function in Python

The sum() function sums a list of values in Python. We can use this sum() function with a list comprehension to get the desired list of values for summation.

We again have to specify n+1 as the upper limit of the range() function.

The following example shows us how to carry out series summation with Python’s sum() function.

sum = 0
n = 5
sum = sum(i for i in range(1, n+1))
print(sum)

Output:

15

Similar to the previous example, we initialized the sum and n variables to store the results and specify the summation range. The list comprehension used inside the sum() function returns values from 1 to n, summed up and stored inside the sum variable.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Python Math

  • Calculate Factorial in Python
  • Calculate Inverse of Cosine in Python
  • Calculate Modular Multiplicative Inverse in Python
  • Fit Poisson Distribution to Different Datasets in Python
  • Reduce Fractions in Python
  • Define an Infinite Value in Python