Trouble with compute_bill


#1

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

I input the following:

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(shopping_list):
    total = 0
    for item in shopping_list:
        total += prices["banana"]
        total += prices["orange"]
        total += prices["apple"]
        
    return total

But, I get this error:

    Oops, try again.
    compute_bill(['apple']) returned 7.5 instead of 2

Can somebody please explain to me what I'm doing wrong? I've been stuck on this exercise for over an hour now.


#2

The error message that you are getting explains what's wrong, doesn't it? Do you disagree with it, or what's stopping you from changing the behaviour of your code to what the instructions describe?


#3

Where am I going wrong?


#4

Indeed, that was the question. And to find out, you'll need to compare what your code should do, to what it does. The error message is already telling you a whole lot about that, so you'll need to begin by determining if you agree with it. If you do, then you can compare how you would do the task manually to what it is doing. If you don't agree with it, then you might have misunderstood what your code is supposed to do.

Where you're going wrong in fixing the problem is that you're trying to find out where the mistake is without investigating. Can't find what you're not looking for.


#5

I think I get it. I think.

The way I wrote it, the code was thinking that the entire string after for item in shopping_list was just for prices["apple"], as opposed to adding all three independently.

I was focusing too much on a single string in the code, as opposed to the entirety of the code.


#6

In your code, you are adding all the prices of all the foods over and over. By typing:
total += prices["banana"]
total += prices["orange"]
total += prices["apple"]
you are defeating the purpose of the for loop. That is the point, that your code loops vs. you typing all the food items in the list. Try the following:

Write your code below!

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


#7

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