12. Stocking Out - Code looks OK but I got error message


#1


Please someone help me out what's wrong with my code.
I have the following error message:

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

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

#2

Add [stock] to your if statement,

to,

if stock[item] > 0: So that while your code is looping it can check if the item is in stock


#3

Thanks a lot. It solved the bug.


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

This gives me the error "Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana caused the following error: global name 'item' is not defined"
Does anyone know why this causes this? To me my code looks like the code above(except including the fix)


#5

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

return total

Instead of ' if item > 0, write if stock[item]>0
That worked for me

Summary

This text will be hidden


#6

shoppinglist = ["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]
stock[item] -= 1
return total

print compute_bill(shoppinglist)

Hi ! Can you tell my why? I think that everything is good... Error below :

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}

Please, help.


#7

My only problem was that there was no -= in my code


#9

It says in the error not to call the function compute_bill because it changes the value of the stock. So remove the last line from your code and it should be fine


#10

Ohh... Yes, now is good. Thanks !


#11

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