Stocking out


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 item in food:
        if stock[item] < 0:
            total = total + prices[item]
            stock[item] = stock[item] - 1
    return total
    print total
food = compute_bill(shopping_list)
print food

My code keeps returning "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." And, after looking through the countless other forum posts and adjusting my code accordingly, I can't seem to figure out what the issue is.

Can anyone help?


You only include items that have negative stock
(add prints in your code to follow along in what it does and observe where it behaves differently from what you want)


Agreed, notes would be helpful. As for only including item with a negative stock, I'd have to disagree. Apple is the only item with no stock (which isn't negative). And besides, the return error says itself that it should say "7" not zero, which indicates that it's not my list that is the problem but my code.


You get a result of 0 because no stock is negative - so nothing is added - a total of zero


You're right. I used the wrong sign.

Thanks for the help.


I'm not suggesting that you make notes/comments (self-explanatory short code, there's no need), rather that you add prints that explain what is going on, so for example you might make your code print out:

entering compute_bill(['apple', 'banana'])

current item: 'apple'
stock: 0
price: 2
not adding because it's out of stock
new total: 0

current item: 'banana'
stock: 6
price: 4
adding one banana, new stock: 5
new total: 4

returning final result: 4

With that it's just plain English, check where it goes wrong and fix the corresponding code.


Ahh gotcha. Good advice. I'll do that moving forward.


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