11. Making a Purchase


#1

Hey there. I’m having trouble understanding why this is different from the example.
Looking at the example I wrote out

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

Which, as we know, is not the right answer. But when I look at the correct code…

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

…there seems to be a disconnect between prices and the variable food. How do we go from taking the item in food to the item in prices? The example used a list, but prices is a dictionary. Does that have anything to do with it?


#2

understanding what values food (function parameter) will hold is very important:

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

print compute_bill(shopping_list)

so, food will contain a list of products (apple, pear and so on) which is why we need item as key to get price value from prices dictionary


#3

@stetim94 thank you. I was missing the last part bringing it all back to the shopping list.
Much appreciated.


#4

well, it doesn’t have to be shopping_list, you can also supply a different list with products as argument on function call. I was lazy and used an existing one

The most important thing is that you understand what values the functions parameter will get


#5

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