How to call functions that takes input into a dictionary?


#1

https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/lets-check-out?action=lesson_resume

Error Message
Traceback (most recent call last):
File “python”, line 26, in
File “python”, line 21, in compute_bill
KeyError: ‘o’

I expect the print statement to call the function compute_bill() with orange as the input. The function then inputs the value into the dictionary and runs the for loop and gets the desired output.
Note; I have tried variance of the print statements
print compute_skill[orange]
print compute_skill[“orange]
print compute_skill{'orange”}



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



https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/lets-check-out?action=lesson_resume


#2

compute_bill takes a parameter of type list. When you call it with a string, instead, it attempts to iterate through each letter of the list and then find that letter in stock. Nowhere in stock does the key “o” appear, hence the error. Instead, call the function using your shopping_list variable, which is of type list.

print compute_bill(shopping_list)

#3

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