Something of Value - Code correct but multiplication results are off


#1

Hello Everyone. My code is as follows. Yet, although the module is passed as correct, the results I get from the multiplications are off. Any suggestions why is this happening?

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] + total
    print total

The result printed in the console is as follows:

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


#2

you placed the print inside the for loop, this mean, the updated version of total is printed every run of the loop, if you are only interessted in the final total, place the print outside the loop:

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

#3

Thanks for the reply. Whitespace matters indeed as it seems.


#4

python relies on indention (whitespacing) to tell what is inside a function/loop and so on, at this point in the course, this shouldn't be a surprise


#5

I know. I guess I am just too tired today :slight_smile:


#7

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