On Sat, Dec 26, 2015 at 12:59:45PM +0000, Tahir Hafiz wrote: > Finally getting round to doing some more python. > Stuck on a little online exercise: > "Define a function prod(L) which returns the product of the elements in a > list L." > > Let's say L = [1, 2, 3, 4] > > I have done this so far but it's not quite working: > > def prod(L): > sum = 1 > for i in L: > sum = sum * i > return sum
The variable "sum" is a bad name for the variable. "sum" means the values are added, not multiplied, so the variable name is misleading. But the actual bug in the function is that the last line, "return sum", is indented too far. That makes it part of the for-loop. So when you call prod(1, 2, 3, 4]) the function does: let sum = 1 let i = 1 # first item in L sum = sum * i # 1*1 = 1 return sum # exits the loop and the function, returning 1 You need to adjust the indentation of the last line so that it doesn't return until after the loop has completely finished. -- Steve _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor