11. Making a purchase


#1



Please help! Where is wrong with my code? I checked several times but cannot find why. Thank you in advance!

The error said "compute_bill(['apple']) resulted in a TypeError: 'dict' object is not callable"


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 food in shopping_list:
        total=total+prices(food)
    return total


#2

shopping_list is the global object passed to the function in the call expression:

compute_bill(shopping_list)

food is the local parameter,

for item in food:

#3

Similar error.

# Write your code below!
def compute_bill(food):
    total = 0
    for n in food:
        total += prices[food]
    return total

(Only different from your code in the brackets around food instead of parentheses)
Brought the error message:
Oops, try again. compute_bill(['apple']) resulted in a TypeError: unhashable type: 'list'

Which sounds like a complaint about the input as a list?


#4

Good catch. I ofter leave that for the OP to discover, but it bears mention.

Dictionary values are accessed using subscript syntax similar to a list index.

Argument lists take the form of a tuple, (something, else). Python will treat the following as a function call,

prices(food)

#5

I figured out that I needed to match the variable from "for n in food" to the key I was asking for underneath "total += prices[food]" should have been "total += prices[n]". Working now. :slight_smile:


#6

This is my final answer:

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

Hope it helps.


#7

Yeah I find the mistake. Thank you so much!


#8

This may be just a matter of interpretation as I ran into the same issue.
In my defense the instructions state: "Note that your function should work for any food list." so why would i need to parse it over prices. Of course if we take in context "Ignore whether or not the item you're billing for is in stock." to me when i hear the keyword any food list i immediately took out from my mind the fact that we had to use the previous configured lists. It has been a while since being on this page, but if i recall properly on the Java course (I dont see it any longer or maybe it was a different website, please clarify on this one) there were many variables tested into the function, so if you got 99 out of 100 right it would still give you an error until you managed to put a logic together that could fill all gaps.


#9

PD: Java Script it was...i see it now