Stocking Out: code is supposedly wrong because I'm reducing stock, but I'm asked to reduce stock. Confused


#1

The instructions for this exercise say:
"Make the following changes to your compute_bill function:
While you loop through each item of food, only add the price of the item to total if the item's stock count is greater than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count."

But when I run my code, it says this:
"Oops, try again. stock doesn't look quite right! Make sure to not call compute_bill since it changes the stock! It should contain: {'orange': 32, 'pear': 15, 'banana': 6, 'apple': 0}"

It's saying I shouldn't change the stock? But the instructions tell me to reduce the stock by one, so I'm confused about what is going wrong here.

Here is my code:

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:
            total += prices[item]
        return total
       
for product in shopping_list:
    if stock[product] > 0:
        stock[product] -= 1

total = compute_bill(shopping_list)
print total

#2

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

hi,i think there are some problems with"prices[item]". of course you need modify your code from the beginning of "for" loop.


#3

Hi, I have similar problem, but my code is different a bit:

def compute_bill(food):
    total = 0

    for number in food:
        if (stock[number]>0):
            total += prices[number]
        stock[number] -= 1
        return total

#4
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 number in food:
        if (stock[number]>0):
            total += prices[number]
            stock[number] -= 1
    return total

This one works


#5

So all you did was shift your "return total" one tab to the left and then it worked?


#6

Ah, it seems my problem was it didn't want me to call the function at the end. It just wanted me to write the function. That's it. Not run it.


#7

yep.
I was calling function as well, that's why the code wasn't working at all


#8

GAH I've been banging my head against the wall with this one for about a half hour now. This irritates me that the issue was it didn't want me actually calling the function - what the ■■■■ right?


#9

Haha! I know, right?


#10

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