添加来自for循环的结果

huangapple go评论60阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年4月17日 18:18:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定