A Day at the Supermarket


#1

I have 2 similiar codes and can anyone explain why one returned str while other returned integers??
code 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 item in food:
        total += food[item] # <====here!!!!!!!!!!
    return total
print compute_bill(prices)

code 2: -

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 item in food:
        total += prices[item] # <====here!!!!!!!!!!
    return total
print compute_bill(prices)

both printed out the correct total of price, which is 10.5
however the first passed the test of the codeacademy while the 2nd codes returned a type error.


#2

you call the function passing it the prices as argument:

print compute_bill(prices)

however, the exercise will call your function with shopping_list as argument:

print compute_bill(shopping_list)

now, food contains a list with strings. so now food[item] will be a string, causing problems.

Thinking about it, it has to make sense that you call compute_bill with shopping_list as argument? I mean, you want to bill people for what they are buying, not for each item in your stock.