Something of Value


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

Oops, try again. It looks like your code did not print the correct total.

What's error in total

Please help


#2

this line:

total = stock[key] * prices[key]

an equal sign will simply set a value for a variable, you need to add stock[key] * prices[key] to what is already in total, simple example of what you do wrong:

total = 0
two = 2
five = 5
total = two
total = five
print total # will output 5

this will set total 5, but you want to add it together:

total = 0
two = 2
five = 5
total = total + 2
total = total + 5
print total # will output 7

i add to what is already in total, you should do the same


#4

Hello,

Here's the problem. In your for loop you call the wrong variable.
What you wrote:
for i in prices:
<indent>total = stock[key] * prices[key]

What should be written:
for i in prices:
<indent>total = stock[i] * prices[i]

Cheers,
M.

p.s. "indent" is just to indicate that there should be indentation there - I just couldn't figure out what sort of markup should be applied on this Q&A site.


#5

hi there,

I had the same problem, which made me a bit confused.

how does python differentiate between calling on a key or a value in a 'for loop'
to make my question more clear, the example below calls on a key and then call on a value, but I don't understand how does Python see the difference:

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

any clarification would be much appreciated.

Cheers


#6

I guess you need to add the value to the total. So if you write
total += prices[key] * stock[key]
, it should work. Because
total = stock[key] * prices[key]
this code gives total a new value. It doesn't add the value to the total.
I hope it can help. I just did it i mean i'm really new for python as well. Sorry if something is wrong.


#11

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