Completed Product (13), but not sure how


#1

So, from doing these exercises, I've found that about half the time, a problem can be solved simply by changing the indentation on "return." However, I'm still not clear as to why.

For exercise 13, I entered

def product(numbers):
total = 1
for num in numbers:
total *= num
return total

which gave me:

Your function fails on product([1, 2]). It returns 1 when it should return 2.

I then changed the indentation for return thusly

def product(numbers):
total = 1
for num in numbers:
total *= num
return total

and had it work. Can someone explain this to me?
`


#2

Why changing the indentation of your return statement makes your code work is because your return statement is returning the items in your for loop. And by putting it at the same indentation column, it shows the python interpreter what line it is getting the return value from.


#3

a function ends once a return keyword is reached. So if you have this:

for num in nubers:
   total *= num
   return total

the for loop stops after the first run, since the function ends (because a return keyword is reached, while on the other hand this:

for num in nubers:
   total *= num
return total

will run the entire for loop before returning. It is a huge difference