Skip to content
Advertisement

Series Summation using for loop in python [duplicate]

Let’s assume this series

JavaScript

in c with for loop we can easily done this

JavaScript

in python i am able to done this using while loop

JavaScript

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

JavaScript

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:

JavaScript

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

JavaScript

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:

JavaScript

or in a more succinct, “Pythonic” way:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement