# Product - Explanation needed

#1

Hello, am stuck at this exercise, i just can't think of solution for it until i came across the code below. The code works fine but can someone explain to me how the code works because i don't understand it, i don't just want to copy and past. And is this the only way to solve the exercise?

``````def product(lst):
total = 1
for i in lst:
total *= i

#2

does kind of defeat the purpose of the exercise, doesn't it? Why did you not make a topic with your code how far you got? Then we can help you with that.

then don't and write your own solution? There are multiply ways to solve this problem.

Have you tried to add a function call and print statement to see what is happening so you can better understand the code?

lets rewrite this line:

``total *= i``

to:

``total = total * i``

so in short, we loop over the numbers in `lst`, and multiply them with total, and store the result of this multiplication in total.

#3

Hi,
i tried this code first. obviously it didn't work. but i realized that i am not sure when to use "range" in the for function:

my initial code:

``````def product(number):
result = 1
for n in range(0,len(number)):
if n > 0:
result *= n
else: return "number is zero"
return result

print product([4, 5, 5])``````

then i removed the range portion to this:

``````def product(number):
result = 1
for n in number:
if n > 0:
result *= n
else: return "number is zero"
return result

print product([4, 5, 5])``````

i get the calculation parts correct but the error message is as follows:
"Oops, try again. Your function does not return an int."

then i removed the if and else condition to this :

``````def product(number):
result = 1
for n in number:
result *= n
return result

print product([4, 5, 5])``````

and i was able to pass.

so can some one please explain 1) when to use the "range" in for loop. 2) why my second code had that error.

Thank you.

#4

range gives indexes which you can use to manipulate the list, so the only time i would use range is if i need to manipulate the list. which you don't, you can still use range, but it makes things more complicated.

the exercise will also test negative values, then this condition: `if n > 0:` is false, a string is returned (a function ends the moment a return keyword is reached), while the exercise expects an integer

#5

omg thank you.

the exercise will also test negative values, then this condition: if n > 0: is false, a string is returned (a function ends the moment a return keyword is reached), while the exercise expects an integer

that makes sense. i was using the" if " function here to avoid multiplication by zero. but i manged to solve that too. thank you. you are the best.

Ps: i also sent a message to you regarding the same topic. Sorry.

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.