# What is the purpose of initializing a variable to zero outside the loop as in page 9 For Loops in 'Lists and Loops'

Hi all, i’m fairly new here. I am struggling to understand the last, bottom, display of the three on Page 9 For Loops in Lists and Loops on the Python Fundamentals. I fail to understand the idea of a_sum = 0 and then how this plays into the output. I seem to be okay with the concept of loops and had practiced some of my own but this particular idea confuses me. Any help would be appreciated.

SS

I think you have a doubt regarding the below image

So the reason for a_sum = 0 is

We need to declare a variable before the for loop in order to store the sum of values in the for loop

If we don’t declare a_sum = 0 before the for loop we will not be able to save the sum of values in the list for future use

Because as shown in the image above if a_sum is not declared we will get an error while using it to store the result

a_sum = a_sum + value

So to store sum so we can use that sum in future we have to declare a_sum before the for loop

It is important to declare a_sum to 0 because if we want to add some value to it later we need it to be initialized to 0 first

Understanding the output

Initially before the for loop value of a_sum is

a_sum : 0

Now for loop starts

First Iteration
a_sum = a_sum(0) + value(1)
So a_sum after 1st iteration
a_sum : 1

Second Iteration
a_sum = a_sum(1) + value(3)
So a_sum after 2nd iteration
a_sum : 4

Third Iteration
a_sum = a_sum(4) + value(5)
So a_sum after 3rd iteration
a_sum : 9

3 Likes