A DAY AT THE SUPERMARKET Something of Value


#1

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

I am not getting why we need to add total = 0.
Does anyone know why ?


total = 0 # What this does actually?
for key in prices:
  print key
  print "price: %s" % prices[key]
  print "stock: %s" % stock[key]
  total += prices[key]*stock[key]
  print total 


#2

+= is a shorthand, without the shorthand it would be:

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

if you don’t define total beforehand, you will get a variable referenced before assignment error

and 0 is just a convenient value


#3

That easy. Many thanks for quick response!


#4

yes, its that easy. All good now?


#5

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