Skip to content
Advertisement

Series Summation using for loop in python [duplicate]

Let’s assume this series

1+2+3+....+n

in c with for loop we can easily done this

for(i=1;i<=n;i++)
{
    sum += i;
}

in python i am able to done this using while loop

while(num <= n):

      sum += num
      num = num+1

but i can’t do it using python for loop

Advertisement

Answer

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 Rauch’s 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, there’s 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 shouldn’t use it as a variable name; this is why I’ve used summation here instead.

Because you might find this useful going forward with Python, it’s 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)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement