Something of value


#1

prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}

total = 0

for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total += prices[key] * stock[key] + total
print total

What's wrong with this code?


Something of value
#2

Did you loop through prices a second time after total = 0?


#3

Yes... tried changing that but it's still not working.


#4

Try using just an = sign not +=


#5

if you still have problems, post an updated version of your code


#6

change this : total += prices[key] * stock[key] + total
to
total = prices[key] * stock[key] + total
you need to add total only once


#8

A quick question: why does it work with +total at the end and not without it? That doesn't make sense to me, and I'd like to know the "why." Thanks.


#9

because that is how you update variable, you need to include the current value otherwise you just overwrite the variable with no respect to with what value is already stored in total


#10

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