英文:
Adding results from a for loop
问题
It seems that you are trying to calculate the total value for each product in your inventory based on their quantity and cost, and then summing up these values. The issue you're facing is that you only have the last valueperproduct
calculated, and you overwrite it in each iteration of the loop. To fix this, you can modify your code like this:
total = 0 # Initialize total outside the loop
for i in inventory:
indexlist = inventory.index(i)
valueperproduct = inventory[indexlist] * cost[indexlist]
total += valueperproduct # Add the value to the total
print(valueperproduct)
print(total) # Print the total value after the loop
This way, you'll calculate and accumulate the value for each product correctly and then print the total value after the 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?
答案1
得分: 0
你在for循环中声明了'valueperproduct',因此在每次迭代中都会覆盖先前的值。我认为在循环外部声明数组并追加值会得到所需的结果。
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论