I think I know what is wrong, but not how to fix it?

#1

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:
total = stock[key] * prices[key]
print total

When I run the code it list the individual totals for the keys but I believe the lesson is asking for the grand total of that. I need to add the numbers together some how but for some reason it escapes me. If anyone knows a lesson I could go back to, or just a general hint would be appreciate it!! Thanks!

#2

In python code indentation is important

If you use a FOR-loop
to express its code-block, you do a 4 space indentation.

To express the end of the FOR-loop-codeblock
you leave the prior indentation
for instance

total = 0
for key in stock
total = total + stock[key]
print total

This will print the total =stock=

#3

Your code looks great, I think it’s without indentations as it was copy pasted…
To get the grad total you have to think of the for loop as a multiple step process. What I mean is that, that every time you go through the loop something more happens but you somehow have to save the result from the prior process.
For example if in our dictionary we have 3 item, the sum will be executed three times, after each time the sum gets executed we have to keep/save the result.
Your ca replace the total - stock[key]*price[key] with something like this:
total = total + stock [key]*price[key] - otherwise in each loop you attribute it a new value without saving the old one you calculate in a prior step
total += stock[key]*price[key] - or this cleaner version could replace your line

Hope I explained it good enough for you to understand.

#4

When I saw your comment this morning it hit me like a ton of bricks. Thanks so much!

#5

Unfortunately the indentations was a big problem however you did a wonderful job explaining the other half of my problem I had not seen yet, that of the value not being saved in each loop. Thank you so much!!!