Something of Value - got it right but not sure I did it the correct way?


#1

I managed to get the correct answer - but it seems that doing “total = total + prices[key] * stock[key]” to add it it to the overall total is a weird way to do it… Is there a more efficient way of doing it? Maybe by storing “prices[key] * stock[key]” to its own variable??



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

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



#2

Hi @chrisw96,

You could use …

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

See 6.3.1 Augmented Assignment statements.


#3

Hi there @appylpye, thanks so much - that helps a lot :slight_smile:


#4