Question about Stocking Out


I’m curious about something in the “Stocking Out” exercise. We are instructed to subtract from the stock after we add the price to “Total”. We’ve already checked for available stock at this point, so I’m wondering what the reason we should change the dictionary after adding to the variable is. I imagine it has something to do with how code should be structured that I have yet to learn? It seems to function correctly if I do it the opposite way ( except the first time I tried it said my “total” line was indented improperly, worked fine after that).

I just want to know if there’s something more to this that would be good to know in the future. Thanks for the help!

EDIT: So I just thought about it after posting and realized you wouldn’t want to subtract from the dictionary (or change it), before using the values in it to add to the variable “total”. Essentially you shouldn’t change a value you need to use before using it.

Am I correct about this? Or am I still missing something? Thanks again!!

total += prices[item]      
      stock[item] -= 1


stock[item] -= 1
total += prices[item]


Your thinking about that is correct.

First, we find out how many of a certain item are available in the supermarket’s stock. If the item is available, it gets purchased, and then we subtract 1 in order to update the record of how many of that item remain in stock, so that we are ready to process the next purchase.

If for some reason you want to do so, you could change a value of a variable that you need before using it. However, that would require you to either save the value in another variable first, or to re-compute the original value, which would make your program more complicated than necessary. Keep things simple unless you have a good reason for doing otherwise.

Simple is better than complex.

The above is quoted from The Zen of Python.


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