Something of Value


#1



Something of Value


With script below, CodeAcademy gives me the correct answer.


However, i expect to multiply prices * stock by each same item: Like apple * apple, and etc. Right now i get incorrect numbers. It seems like it is multiplying what ever it wants. Where did i make a mistake?


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


#2

It does what you expect.

results

orange
48.0  # 1.5*32=48

pear
45 # 3*15=45

#3

you need to add total to prices[key] * stock[key] = total


#4

Actually you don't need to add TOTAL. it does not make any difference.
The I found the answer i was looking for. I just needed to assign total = 0 after the FOR. When it prints the result: pear * pear, apple * apple ant etc. not adding everything to TOTAL sum.

I hope you understood my point. :slight_smile:


#5

I did the following and works fine. I don't understand yet why the first variable has to be assigned 0. Otherwise, you need to find the way to add all the items' values, which I did with total += value. You can also write print key before print value to get the items' labels. The script runs correctly with or without (although the instructions call for numbers alone, no text).

total = 0 #WHY 0???
for key in prices:
    value = prices[key] * stock[key]
    print value
    total += value
    
print total

#6

Not elegant, but it worked! I had to play around with it for a while. The instructions were a bit vague, probably on purpose.

total = 0

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

print total

#7

total=0
for i in prices:
     total+=prices[i]*stock[i]

print total

works fine for me.


#8

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