9. Why doesn't: total = prices[key] * stock[key] print totalwork?


I'm told to multiply the stock by the price and print it as 'Total'.

My answer is below, figured I'd redefine total. it prints the desired result correctly, but instead of moving on,I get a error: "looks like the code didn't print the correct total."

I've looked at other posts and they say that I should declare a new variable inside the for loop and add that to the 'Total' that I previously defined, but that just doesn't seem efficient to me.

Am I breaking some kind of Python rule or is Codeacademy playing up again?

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

for key in prices:
    total = prices[key] * stock[key]
    print total

  1. total is expected to accumulate... Eg. t = t + a * b
  2. Wait for the loop to finish before printing.


Right, so I think I understand that total is a pre-defined function, hmmm.

found the solution by adding a 'x'. total += prices[key] * stock[key]

I also 'waited for the loop to finish before printing' by removing the indent in print total. Thanks!


That is the abstraction of,

which you intuitively gravitated toward. Kudos.

total is a singular cached value in memory. The math your program is doing is a function, in math terms, but not in program terms.


a * b is a math function in two variables.

y = x1 * x2

c ** 2 = a ** 2 + b ** 2

The latter is a relation expressed in three variables. Where any two are known, the third can be determined. Too bad the computer is not capable of realizing this.


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