Search code examples
pythonfor-loopsum

Adding results from a for loop


I can't seem to get the results from a for loop equations to add up.

for i in inventory:
    indexlist = inventory.index(i)
    valueperproduct = [(inventory[indexlist] * cost[indexlist])]
    print(valueperproduct)

total = 0
for i in valueperproduct:
    total += i
print(total)

This is what it returns:

0 pen 2 1.5
1 watch 3 2.5
2 ruler 4 4.5
3 bike 5 3.3
[3.0]
[7.5]
[18.0]
[16.5]
16.5

What did I do wrong?


Solution

  • You have declared 'valueperproduct' in your for loop and so with each iteration you are overwriting the previous values. I think declaring the array outside of the loop and appending to it will give the desired result.

    valueperproduct = []
    for i in inventory:
        indexlist = inventory.index(i)
        valueperproduct.append(inventory[indexlist] * cost[indexlist])
        print(valueperproduct)
    
    total = 0
    for i in valueperproduct:
        total += i
    print(total)