KeyError: 'p' when using Python 2.7


#1

Hi,

I have been working though the lessons on python and am confused about how the "for loops" work in code academy.
When I use the correct answer for "Making a Purchase" and put this in to a ".py" script and execute this on my local python environment I get the following error, but this returns a successful result in the online editor:

KeyError: 'p'

The Python code I am using is as follows:

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

compute_bill('pear')

#2

Hi!
I could be wrong but I think the program is doing that because it's literally taking the letter 'p' in pear as the 'x' in food. If the argument passed to the parameter 'food' is to be only a single string, I think something like this might work:

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

Of course if you need to add a list of items, for example, it gets trickier. :wink:

Good luck!


#3

after looking around at some alternative methods *args accepts the string as well as the list and returns the desired result

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(*args):
    total = 0
    for food in args:
        total = total + prices[food]
    return total