A day at the supermarket-Stocking out(12) Help!


#1

Hi, don't know what's wrong. Please help.

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


#2

Using Markdown when posting code lets others see how well you have indented your code.

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

Notice where the the return statement is? It's inside the IF code block, so exits the function on the first iteration of the loop.

def compute_bill(shopping_list):
    total = 0
    for food in shopping_list:
        if stock[food] > 0:
            total += prices[food]
            stock[food] -= 1        # stock needs to be reduced by 1 sold item
    return total
#compute_bill(shopping_list)

#3

it wants you too decrease ammounts if there is product so u can use this:
def compute_bill(shopping_list):
total = 0
for food in shopping_list:
if stock[food]>0:
total+=prices[food]
stock[food]=stock[food]-1
return total


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

Thanks! This was sufficient, it did not require the last line of "compute_bill(shopping_list)", that gave me an error of: "Make sure to not call compute_bill since it changes the stock! It should contain: {'orange': 32, 'pear': 15, 'banana': 6, 'apple': 0}"


#5

Thank you, I now Understand where I went wrong now, and as luminousbeam said you don't need the last line.