Doing sum in for loop

Hi all

I am very new to python, rather very new to programming.

Can someone make me understand logic behind using a variable out side loop for e.g. sum=0, for doing sum in loop, how exactly it is being executed? though it is explained in the course content but still want more clarity.

Hello @sheresd,

Welcome to the community! Your question is not clear. You could probably post more of the code and highlight the part you do not understand.

@sheresd: sum = 0 outside the loop initializes the variable sum for counting/storing of the elements in the loop.

Like @doyinsolamiolaoye says, your question is a little vague but I will attempt to answer it to my own interpretation.

Here is an example:

sum = 0

#randomly initialised list
randomData = [4,1,10,3,5]

# The range function executes before the loop starts
# in this case it makes use of the length of the array through the
# in-built len() function. Every time before the loop executes, it checks
# if the counter i is less than the length of the randomData list
for i in range(len(randomData)):
      sum += randomData[i]

Iteration 1

for i in range(len(randomData)): 
''' i = 0, thus 4 gets added to sum, sum = 4, len(randomData) = 5, i < 5 is true '''
      sum += randomData[i] 

Iteration 2

for i in range(len(randomData)): 
''' i = 1, thus 1 gets added to sum, sum = 5, len(randomData) = 5, i < 5 is true '''
      sum += randomData[i] 

Iteration 3

for i in range(len(randomData)): 
''' i = 2, thus 10 gets added to sum, sum = 14, len(randomData) = 5, i < 5 is true '''
      sum += randomData[i] 

and so on…
Hope this clarifies.

1 Like

Hi @sheresd:

It’s been a long time since you posted, just following up on this. May I know if my answer helped you?

Thanks