General question regarding for loops

hey there,

sorry for the potentially stupid question but just wondering why in the tutorial for Lists and For Loops
that before beginning the loop one must initialise a variable with a value of 0?

rating_sum = 0


If you are referring to lesson 9:

row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5]
row_3 = ['Clash of Clans', 0.0, 'USD', 2130805, 4.5]
row_4 = ['Temple Run', 0.0, 'USD', 1724546, 4.5]
row_5 = ['Pandora - Music & Radio', 0.0, 'USD', 1126879, 4.0]

app_data_set = [row_1, row_2, row_3, row_4, row_5]
rating_sum = 0
for row in app_data_set:
    rating = row[-1]
    rating_sum = rating_sum + rating
avg_rating = rating_sum / len(app_data_set)

You don’t always have to add a variable with 0 but in this case we want to sum up all the ratings and to do that we need to start somewhere, that being 0.
Then we add to that value as we loop through the lists (rating_sum = rating_sum + rating). We are saying the new rating_sum is the current rating_sum plus whatever is in rating in this round of iteration.

Once we are done with the loop rating_sum reflects the sum of all ratings.

1 Like