12. Stocking Out


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<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.>

<What do you expect to happen instead?>
Error:

Oops, try again. calling compute_bill with a list containing 1 apple, 3 pears, 3 oranges and 8 bananas resulted in 45.5 instead of the correct 37.5

Question: I’m not really understanding how dictionaries work when combined with for loops I guess. That code looks like it should work to me. Should I go back a few lessons or am I just missing something very simple?

```python

shopping_list = [“banana”, “orange”, “apple”]

stock = {
“banana”: 6,
“apple”: 0,
“orange”: 32,
“pear”: 15
}

prices = {
“banana”: 4,
“apple”: 2,
“orange”: 1.5,
“pear”: 3
}

def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0: ###Broken
total += prices[item]
return total
print total

print compute_bill(shopping_list)

<do not remove the three backticks above>

#2

edit: Also I would be interested to know WHY its returning 45.5 instead of 37.5.


#3

i am going to give you a push in the right direction, if you need more help let me know. You have 6 banana’s in stock, your code allows me to buy 9. Why? You don’t update your stock after i bought something, which is also explains why the bill is to high: You let me pay for items which you have no longer in your stock.


#4

Sadly, that doesn’t seem to be getting me anywhere with the problem.


#5

what do you mean? It is the problem, you need to update your stock after something is taken out (bought)


#6

When I add

stock -= stock[item]

to the if statement I get an error though


#7

i mean
stock[item]-=1


#8

it seems you are not allowed to call the function, remove this:

print compute_bill(shopping_list)

could you post an updated version of your code if problems still persist?


#9

That allowed me to pass the course (removing the print statement)

However I honestly still don’t understand exactly why it worked. I could swear i typed it exactly like this:
(indentations removed because I dont know how to format it on the message boards)

def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0: ###Broken
total += prices[item]
stock[item]-=1
return total
print total

and it did not work before

I guess I’ll just keep going for now and just repeat the section on dictionaries at a later date.

Thank you for your help.


#10

but you added the stock[item]-=1, and then you removed the print statement (For a reason i do not yet understand the exercise doesn’t want you to call the function)

So you made changes. Which is why it works :slight_smile: