Help Figuring Out For Loop Error


Traceback (most recent call last):
File “python”, line 27, in
File “python”, line 21, in compute_bill
KeyError: ‘b’

I expected the bottom for loop to calculate the total, but I keep getting that error. What did I do wrong? I passed the lesson with it but there’s an error.

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:
    if stock[item] > 0:
      total = total + prices[item]
      stock[item] -= 1
  return total
true_total = 0
for item in shopping_list:
  true_total += compute_bill(item)
print true_total


Hi @gambythe4th,

The compute_bill function is designed to take, as an argument, a list of items that can each serve as a key to the stock and prices dictionaries. However, in this for loop header …

for item in shopping_list:

… you are using item to iterate through shopping_list. During each iteration of the loop, item will represent one of the items in shopping_list. Each of those items is a string. Therefore, you are passing a string to compute_bill here …

  true_total += compute_bill(item)

As a consequence, within the compute_bill function, the loop that begins here …

   for item in food:

… will iterate through the string that was passed to it. Since the first item in shopping_list is "banana", that is what you are passing to compute_bill. Therefore, during the first iteration of the for loop within that function, item is set to the "b" character from "banana". Then this statement attempts to use that character as a key …

      total = total + prices[item]

There, "b" is an invalid key, as it does not occur in prices.

All of the above can be cleared up by replacing these three statements …

true_total = 0
for item in shopping_list:
  true_total += compute_bill(item)

… with a single print statement that passes shopping_list to the compute_bill function.


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