Day at supermarket - error not understood


#1

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

print compute_bill (shopping_list)

I get this error:


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


#2

Somehow 'apple' got added even though there are none. Check your indentation.


#3

As far as I can tell my indents are OK - (I wish there were block terminators instead of indents only..)
I changed location of shopping_list -- getting different error now

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

shopping_list = ["banana","orange","apple"]

Write your code below!

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

print compute_bill (shopping_list)

ERROR NOW
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}


#4

I was just going to say that. When we call it, we change the dictionary before the SCT gets to run the check. Remove the print statement.

The return line is indented too far. It should line up with for, not if.

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

>>> 
>>> print (compute_bill (['apple','pear','banana']))
7
>>>

#5

WOW !
I was under the impression that we are supposed to show how it WORKS!
I guess the code get tested without me running it..

THANKS! I knew my code was correct - but the instructions confused me!


#6

hello, I can’t udnerstand part “stock[f] = stock[f] - 1” in this code. Why we should use it?


#7

Where f is a key name, such as ‘apple’, then stock[f] will be the count of apples in stock.

stock[f] = stock[f] - 1

means we are taking one away from the apples in stock. You will also see it written in the compound assignment form, as follows:

stock[f] -= 1

which is exactly the same operation, only combined for better readability.


#8

A post was split to a new topic: To me 8.5 seems like the correct answer


#9