#12. Stocking Out - HELP


#1

Hi,
Need some help with this. Apparently it results in 2 instead of being 7, whatever that means.
Here is the code.

Thanks for any help people can give me, much appreciated.

Ben :slight_smile:

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 > 0:
            total = total + prices[item]
            stock[item] - 1
        
        elif stock == 0:
            total = total
        
        return total
        print total

#2

a function ends the moment a return keyword is reached. this is currently happening in the first iteration of your loop, place the return outside the loop so the whole loop can run.

frankly, you don't need the elif, it doesn't do anything useful

look at the below code:

x = 5
print x  // 5
print x + 5 // 10
print x // 5
x = x + 5
print x // 10

now what this is mind, look at your stock "update":

stock[item] - 1

that doesn't really update the stock, does it?


#3

Thankyou. I always forget indentation is so important.

Then how would you have a stock update?


#4

indention is rather important in python.

well see how i updated x:

x = x + 5

i set x to its own value + 5, you could do the same for stock items but then minus one


#5

Ok, I thought that would fix it but apparently it gives me 9 instead of 7. Here is the current code.

Thankyou for all your help :slight_smile:

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 > 0:
            total = total + prices[item]
            stock[item] = stock[item] - 1
        
    return total
    print total

#6

here:

if stock > 0:

what is stock? it is a dictionary. you need to check if the item is in the stock


#7

Thankyou so much. That explains a lot.


#8

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