13. Product (problem with conditional)


#1



There seems to be a problem with my conditional. It returns 500 instead of 100.

Strangely, when for each num in numList I print numList.index(num) I'm getting: 0, 1, 1, instead of 0, 1, 2. This might have something to do with why the conditional is failing.

I'm also not sure if "break" is the correct syntax? I've also tried using while, but get stuck in an endless loop.

Any help would be appreciated! Thanks :slight_smile:


numList2 = [4, 5, 5]
    
def product(numList):
    total = numList[0]
    index = 0
    for num in numList:
        if numList.index(num) != ((len(numList))-1):
            total = total * numList[index + 1]
        else:
            break
    print(total)

product(numList2)


#2

This is a problem where we are simply looking up items in a list. There is no need to complicate it with .index(). That is complete overkill, imho.

product = 1                # set to unity
for num in numlist:        # item look-up syntax
    product *= num
return product

It is important to remember that a look-up loop is not sequenced (ordered). The items may be iterated in any order so the index could be jumping around. This will take some extra study on your part, but as it does not directly relate to this lesson, any questions about the concept should be posted in the corner bar. You may also find .enumerate() to be interesting as it relates to your idea.

Again, look for simplicity and concise solutions. If the code is complicated at this stage, then it is a good sign you are going overboard.


#3

its work

def product(a):
    b=1
    for i in range(len(a)):
        b*=a[i]
    return b

#4

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