Series Summation using for loop in python

Series Summation using for loop in python

Python syntax is a bit different than c. In particular, we usually use the range function to create the values for the iterator variable (this is what was in Stephen Rauchs comment). The first argument to range is the starting value, the second is the final value (non-inclusive), and the third value is the step size (default of 1). If you only supply one value (e.g. range(5)) then the starting value is 0 and the supplied value is the ending one (equivalent to range(0, 5)).

Thus you can do

for i in range(1, n + 1):

to create a for loop where i takes on the same values as it did in your c loop. A full version of your code might be:

summation = 0
for i in range(1, n + 1):
    summation += i # shorthand for summation = summation + i

However, since summing things is so common, theres a builtin function sum that can do this for you, no loop required. You just pass it an iterable (e.g. a list, a tuple, …) and it will return the sum of all of the items. Hence the above for loop is equivalent to the much shorter

summation = sum(range(1, n + 1))

Note that because sum is the name of a builtin function, you shouldnt use it as a variable name; this is why Ive used summation here instead.

Because you might find this useful going forward with Python, its also nice that you can directly loop over the elements of an iterable. For example, if I have a list of names and want to print a greeting for each person, I can do this either the traditional way:

names = [Samuel, Rachel]
for i in range(len(names)):  # len returns the length of the list
    print(Hello, names[i])

or in a more succinct, Pythonic way:

for name in names:
    print(Hello, name)

For a series build up your list then add them all together as

n = 10


For 1/n we have

n = 5
sum([1/i for i in range(1,n+1)])


For 1/n^2 we have

n = 5
sum([1/i**2 for i in range(1,n+1)])


Series Summation using for loop in python

This works:

def summation(num): 
    sumX = 0
    for i in range(1, num + 1):
        sumX = sumX + i
    return sumX

summation(3)  # You place the num you need here

As well as this:

def summation(num):
    return sum(range(1, num+1))

Leave a Reply

Your email address will not be published. Required fields are marked *