9. Something of Value


I don't receive any error messages but in the compiler box it posts two very strange values and I can't seem to figure out where they come from. I'm also slightly confused as to where the first 117.0 is coming from (though I think I have an idea that perhaps someone can confirm).

I'm guessing the one 117.0 is coming from either "total = x + total" or "x = prices[key] * [key]"
The other 117.0 is obviously coming form the print line

The really strange part I don't understand is how it's printing/returning 48.0 and 93.0.

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


32 * 1.5 = 48.0 (orange)
15 * 3 = 45 (pear)
45 + 48.0 = 93.0

that is where the values come from, you print total in each iteration of your loop.

(python is a interpreted language, not a compiled one)


hey thanks for the code man


Why does

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

doesn't work ?

total = 0 anyways so why do you have to write total = x + total for it to give you 117.0 ? Because I wrote my code without the + total and it didn't work that's why I came here for help.

PS: I don't know why my second, third and fourth line aren't indented as they are in my edit mode.


because total = x will set the value of total to x. where total = total + x will set total to the result of total + x.

a better way to say this is total = x will simply re-assign total, where as total = total + x will increase total

do you understand what x is?

the bacticks needs to be on the line after the code to make indent show


Why wont

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

Why do we need to make a new variable and add it with total?


this will overwrite whatever is in total, if we do:

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

we add prices[key] * stock[key] to total

in programming, a single equal sign means assign. so without + total, total will just get assigned a new value, overwriting whatever was present in total


Can someone print the code?


posting and asking for answers is not according to the guidelines, i see you already made a new topic and got a reply, that is the way to go :slight_smile:


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