[Tutor] the products of an element of a list

Peter Otten __peter__ at web.de
Sat Dec 26 08:42:39 EST 2015


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
> 
> 
> Code seems to print the right value in REPL (i.e. 24) just a for loop
> though !?!
> Think I am not seeing something obvious.

Look at the indentation. When does execution of the function end? Where 
should it? 

If you don't see it yet use another example list, one that doesn't start 
with 1. 

Example: what does

>>> prod([2, 3, 4])

return? Is the for loop entered? If yes, for how many iterations?




More information about the Tutor mailing list