13/15 Product - "total" inside vs outside the loop


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/3

Hi guys, I have passed this question 13/15 - product. At first I didn't, using the code below:

        def product(lst):
            for i in range(len(lst)):
                 total = 1            
                 total *= lst[i]
            return total

After that I amended my code by shifting the 'total = 1' outside the loop:

def product(lst):
    total = 1
    for i in range(len(lst)):
        total *= lst[i]
    return total

I am a total novice in IT and programming, and I am embarrassed to say that to date, I can still get confused about loops, especially when it comes to yielding a total amount. Can someone please explain to me how 'total = 1' inside and outside the loop work differently? Really appreciate your kind help.


#2

we can do an example, let's say we have this code:

total = 0
for i in range(10):
    total += i
print total

total will print 45 (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9), make sense? We add i each to total each time, result in the sum of the numbers 1 till 9 (9 included)
however, if we do this:

for i in range(10):
total = 0
    total += i
print total

total would be 9, each time the loop runs, total is resetted to 0. So, the last time the loops run, total is reset to 0, 9 is added, then 10 is not smaller then 10, so the loop doesn't run any more, total is 9. Hope this helps


#3

Hi stetim94, your explanation is very clear! Thanks a lot for your help and patience with me!