Something of value


#1



9. Something of value


I am wondering why this code does not run. I have found the solution but this was my first attempt.
The interpreter gives 0 for an answer and i was wondering why you can't write the output of prices and stock directly to total.


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


#2

this:

total = prices[x] * stock[x]

will re-assign a new value to total without bothering what is already stored in total


#3

But the value of total at the moment is 0 so it wouldn't really matter right?
The end goal is to see the total amount of the groceries so eventually i want to see the newly assigned value.

Or am i thinking in the wrong direction?
Thanks for the info so far!


#4

in way you are thinking in the right direction, but not completely, look at this code, it mostly yours with some added print statements:

prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

total = 0
for x in prices:
    print "price for all", x, ":" ,prices[x] * stock[x]
    total = prices[x] * stock[x]
    print "total price for all items: ", total
print total

so here:

print "price for all", x, ":" ,prices[x] * stock[x]

i want to see how much it would cost me to buy all items of product x.

then i print total here:

print "total price for all items: ", total

i added a string so we can see which print statement is which. As you can, see total will not increase because we just re-assign total, it will just contain the price of item x, while total should contains the prices for all items

the price should be 117.0 at the end, the price to buy all apples, bananas, oranges and pears. As you can see, this is clearly not happening


#5

I think i got it! Thank you very much for explaning it more in depth.


#6

My totals are backwards. Grand Total should be the very end total but anyway. Just added on to stetim94 comment

grand_total = 0
total = 0
for key in prices:
print "price for all", key, ":" ,prices[key] * stock[key]
grand_total = stock[key] * prices[key]
total = grand_total + total
print total


#7

And what is your question?


#8

@hansieeeee

You stated that you got it while a solution is yet to be provided to your problem indeed.

@stetim94 clearly state that his solution should ideally print out a total value of "117.0 at the end"

Please i still seek the solution to this problem i will advise you to mark the as unanswered so we can get help asap.Thank you


#11

Your response was my solution, thank you!


#12

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