A Day at the Supermarket( 9. Something of Value )


#1

https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/something-of-value-?action=lesson_resume&link_content_target=interstitial_undefined

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]
  
  
for x in prices:
  total = 0
  n = prices[x] * stock[x]
  print n
  total += n

print total

could someone please explain why the total is 0 if i put the code"total = 0 " in the for loop?
thank you very much.


#2

by placing total = 0 in the for loop, each iteration of the value of total gets re-assigned to zero, and you will never get to correct total/sum.

so the value of 0 is the last product processed by the loop. If the final result is zero, apple is the product for the last iteration. (dictionaries are unordered)


#3

I get it, thank you very much!


#4