Stocking Out


#1

Hi, I am stuck on "A Day at the Supermarket, Stocking Out".

I have submitted the following code and received the subsequent error. My guess is that the code is tripping because there's an apple on the list but the stock is 0. I'm not sure what I've done wrong though. Can you please provide some guidance? Thanks.


shopping_list = ["banana", "orange", "apple"]

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

# Write your code below!
def compute_bill(food):
    total = 0
    for product in food:
        if stock[product] > 0:
            total += prices[product]
        stock[product] = stock[product] - 1
        return total

ERROR:
Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in 0 instead of the correct 7


#2

Two things, and they're both because of your indentation. All of your code is correct, but two lines are in the wrong place. :slight_smile:
First,

stock[product] = stock[product] - 1

needs to be indented once so that it's inside of the if statement, because you only want to take away from stock[product] if it's also getting the price added to the total . (sorry if that doesn't make sense).

And the second problem is where you return total. You don't want to return total in the for loop, because in the first iteration of the loop, the function will end because once a return command is reached, the function is done.
So you want to unindent

return total

I hope this helps!

P.S. You can do

stock[product] -= 1

if you would like instead of

stock[product] = stock[product] - 1

#3

So helpful! Thank you very much!


#4

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