# I think this is the right place to post this

#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

I’m confused as to why the line of code I used to subtract a value from the dictionary needed to be placed outside of the IF “function”, surely this means that in the case of apple, the IF loop would come up false and then not run, leading us to the line of code that subtracts 1 from zero, and should give us -1; or are you saying that when an IF loop comes out false it terminates the rest of the loop for that iteration? that would be the only explanation but I wanted confirmation

``````
def compute_bill(food):
total = 0
for x in food:
if stock[x] > 0:
total += prices[x]
stock[x] += - 1
print stock["apple"]

``````

#2

edit, I meant IF function and not IF loop…

#3

In truth the statement does need to be inside the if block.

``````stock[x] -= 1
``````

We would only decrease the item count if we did in fact add one (by value) to the shopping cart total.

This brings up a different question… Where did this code come from?

Aside

With respect to choosing variable names, we can look to the discussion text for a clue of what would be the most appropriate variable name to use in our solution.

Eg. (my bolding)

Now you need your compute_bill function to take the stock/inventory of a particular item into account when computing the cost.

Ultimately, if an item isn’t in stock, then it shouldn’t be included in the total. You can’t buy or sell what you don’t have!

Which gives this slightly more readable (self-documenting) code…

``````  for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
``````

Rationale

`x` is very common to maths, signifying as it does an independent variable in a function or relation. In programming, used in the same respect would be reasonable, especially if `x` referred to a number.

When we use `x` in a look-up loop, which `for item in food` would be, the value is a string, not a number, so use of `x` as the variable is rather arbitrary and insensitive to the reader’s perception of what it is referring to.

We can make our code as clever as we like, but if others are expected to understand it we need to write it for them, not ourself. That is why there are Style Guides, and an hundred unwritten rules with regard to self-documentation of code, particularly through our choice of variable, data structures and function names.

#4

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