Increment operator


#1

total = total + prices[key] * stock[key]

This particular line of code executes correctly when I have it written like it is above. However, when I change it to total += prices[key] * stock[key], it throws an error for reasons unknown to me. Why is this happening, since both statements are essentially the same?


#2

both should work, could you post your full code, both the correct version and the version that causes an error?


#3

Erhhmmm... That's strange.

See this:

total = 0
total1 = 0
prices = 2
stock = 4

total = total + prices * stock
print total

total1 += prices * stock

print total1

Both gives 8 as answer.

Please post yours!


#4

Code below:

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
    total +=  prices[key] * stock[key]
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    
print total

#5

Your code is fine, it shouldn't throw an error. Weird, maybe some cache problem? Try a different browser. Either way, it is a minor detail, both work, nothing to worry about. You got the essence of the exercise