This is suppost to print 10.5,but is obly printing 1.5. Why?


#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
}

def compute_bill(food):
total= 0
for x in food:
total += prices[x]
return total
print compute_bill(prices)

I am adding up all the keys in the prices dictionary. Why isn't it working?


#2

Hi @bob1352 ,

Because the code that you posted is not formatted, it is difficult for other users to read and debug it. After code has been pasted into the editing window for posting, you can format it by selecting it, and then by clicking the </> button above the editing area. This will enable us to see important details, such as the indentation and underscores.

Since we cannot see your indentation, we can only make a good guess. You may have indented your compute_bill function in this manner, which is incorrect ...

def compute_bill(food):
    total= 0
    for x in food:
        total += prices[x]
        return total

If that is what you did, then the return statement executes during the very first iteration of the for loop. In that case, the price of only one item in food got added to the initial total of 0. Since a dictionary is unordered, it is possible that the item was the one with the key, "orange". That would account for the total of 1.5.

Remove one level of indentation from the return statement, so that it is no longer part of the for loop ...

def compute_bill(food):
    total= 0
    for x in food:
        total += prices[x]
    return total

Also be aware that the real goal of this lesson is to eventually add up the prices of the items in shopping_list. During the final exercise, you can do this ...

print compute_bill(shopping_list)

But if you do that in the next-to-last exercise, Codecademy will yell at you. :fearful:


#3

I copy/pasted your code and still got an 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

Heres an image. I have been stuck on this problem for months now.


#4

I believe you copy-pasted your own code!
What are the instructions saying about the stock, do you see any code that matches that? What would code for that behaviour look like?


#5

I don't think I copy-pasted my own code??? I checked for all indentation errors. I don't understand the questions you are asking me?


#6

@geomaticmashups only posted your code so if you copied from their post, then you copied your own code.

The instructions are to only sum the prices of items that are in stock, so your code has to contain the logic for carrying that out. Currently, your function does not mention the stock at all, so it seems unlikely that the stock is considered.