I have a function similar to the following:
def getCost(list):
cost = 0
for item in list:
cost += item
return cost
and I call it as so:
cost = getCost([1, 2, 3, 4])
This is GREATLY simplified but it illustrates what is going on. No matter what I do, cost always ends up == 0. If I change the value of开发者_StackOverflow社区 cost in the function to say 12, then 12 is returned. If I debug and look at the value of cost prior to the return, cost == 10
It looks like it is always returning the defined number for cost, and completely disregarding any modifications to it. Can anyone tell me what would cause this?
This should solve all of your problems (if summing the list items in cost is indeed what you're trying to do:
def getCost(costlist):
return sum(costlist)
It accomplishes the exact same things and is guaranteed to work. It's also much more simple than using a loop and an accumulator.
精彩评论