Oops, try again. compute_bill(['apple']) resulted in a TypeError: list indices must be integers, not str


#1



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


I keep getting this error message, though I believe I am getting the correct result of 10.5 :

Oops, try again. compute_bill(['apple']) resulted in a TypeError: list indices must be integers, not str


Replace this line with your code. 
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 += food[item]
    return total
    
print compute_bill(prices)


#2

yes, because here:

print compute_bill(prices)

you supply prices as argument, however, compute_bill will be a list with products the customer will buy:

print compute_bill(shopping_list)

the exercise will also test lists, not dictionaries, as you can see in the error message


#3

Thanks for the response!

I was to get the function to work, and I understand what you meant with the comment "the exercise will also test lists, not dictionaries, as you can see in the error message" but I still don't understand how you determined that through the error message:

Oops, try again. compute_bill(['apple']) resulted in a TypeError: list indices must be integers, not str

can you explain?

Thanks!


#4

compute_bill(['apple']) is a test case by the exercise, so then we can simply add the test case to our code:

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

to see why this test case fails


#5

I had the same issue and I understand now that we have to use the "shopping_list". However, I still can't get my code to run. What am I doing wrong?


#6

food[item], food is a list and item could be a item (apple, banana) customers want to buy, but lists can only be accessed by index, not by item, maybe you want to have the price of item so you can add it to total?


#7

A post was split to a new topic: Compute bill


#8

I am getting the same error, but I cannot figure out where this error is coming from. Everything sounds right for me.


#9

and you also read this topic? And both explanations you don't understand, what do you not understand about it?


#10

Got it. I figured out what I was doing wrong.

Thanks for your assistance. I appreciate it.


#11

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