Product


#1

def product(integer):
    l = 1
    num = 0
    for num in integer:
        l *= integer[num]
        num = num + 1
    return l

What's wrong with the code? Its giving error as - Oops, try again. Your function crashed on [1, 2] as input because your function throws a "list index out of range" error.


#2

In the first case, what is integer? Is it a number or a list, or some other object?

for num in integer:

The above line suggests it is an iterable, which would not be an integer unless we made it into a list of numbers, first.

Now that line totally throws one off since num is a value in the list, not an index.

l *= num

Let's think of what we are passing in as arguments, and what to expect as return values.

arguments  => list of numbers
return     => product of the list

def product(numbers):

The parameter describes the expected arguments. In this case we are expecting numbers, so that's a good name to use. At this point, a list, tuple, or even a set would be doable, and they don't have to have this name. Better, actually if they don't. Keep this one local and unused elsewhere owing that it is a data structure, not a value.

l is the least favorable letter to use as a variable name, just so you know. Even variable names that start with l can be tricky, as we witnessed in another topic a few days ago. It is so very often mistaken for a 1 (one) that one favors to avoid its use as much as possible.

If anything use a letter that jumps out.

p = 1

The first question, 'what is p?' should pop up for a reader. Scanning the code one would see,

p *= num

and the question would be answered. p is the product of the numbers so far multiplied in the list.

Impossible in a value based loop. Does nothing.


#3

Thanks a lot, your reply did make me learn a lot. Thanks again. :slight_smile:


#4

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