9. Something of Value - Need Help!


#1


I am having issue with the below code, Please help

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

The Error I'm getting is Oops, try again. It looks like your code did not print the correct total. Please help me in resolving the issue.

The output I got is as below:


orange
price: 1.5
stock: 32
48.0
pear
price: 3
stock: 15
45
banana
price: 4
stock: 6
24
apple
price: 2
stock: 0
0
None

Whats wrong with the above code?


#2

according to the exercise you would have to make a separate loop outside the already existing loop, you can do this.

If you want to use the already existing loop, that is also possible (not really what the exercise wants, but okay):

# declare total here outside the loop

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    # add prices * stock here
   

# print total here, outside the loop

see comments in the above code. No need to create a second loop if you want to take this approach


#3

one more thing, you need to add prices[key] * stock[key] total:

total = total + # add prices times stock

otherwise, total gets overwritten every time, rather then adding to it


#4

Thanks @stetim94, that helped.


#5

did you resolve the issue? If so, good to hear

If not, see if with the new provided insight you can solve it. If not, post an updated version of your code and i will help you further


#6

Yes @stetim94 it's got resolved. Thank you very much again.


#7