Error: compute_bill() returning 4 instead of 10.5


#1



https://www.codecademy.com/en/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096


Error message: compute_bill(['banana', 'apple', 'orange', 'pear']) returned 4 instead of 10.5


I really don't get what's wrong with it. Does the price of the item not mean the same as prices[item] when they have the same key, and why does it return 4 instead of 10.5?
Isn't it automatically supposed to use shopping_list instead of whatever ['banana', 'apple', 'orange', 'pear'] came from? Could someone post the correct answer so i can compare with it, since there's no hint either?


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


#2

The return statement is now in the for. That is why your functions returns a price of the first item in the food list.

You just simply have to decrease indentation level of the return statement:

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

#3

Well that's pretty stupid.
In the instructions of lesson 9. Something of value, step 4 states: "Finally, outside your loop, print total."
In lesson 12, step 4, it simply states "Finally, return the total." without mentioning indentation, and since it didn't, i naturally assumed it meant inside the for loop. Am i crazy to be left confused and assume that if it wanted me in indent it outside of the loop it would mention it like it did before, and since it didn't i didn't have to?

Someone should update it.
Thanks anyway.


#4

Well, there is an idea behind this. Codecademy suspects that after few exercises users understand the meaning of the code. So if you want to calculate prices of all the items in the food list you simply must return the calculated value after the for loop (summing prices of all products).

And, to be honest, this is a pretty unique problem. Users usually understand what is going on and what they have to do in this exercise. And this is why it will not be updated. This is not the bug.

I don't want to offend you in any way, I am simply trying to show you a different perspective. Just take some time and think about your previous code, does it make any sense to put return inside the for?


Programming is not easy. Confusion is sometimes required, but that is why we are here trying to help and explain concepts.


#5

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