Making a purchase


#1

Hi, This is my code:

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

print compute_bill(shopping_list)

My question is, In the compute_bill function why can’t I just say “total += item” instead of “total += prices[item]” for my code to work? Thanks!


#2

total += item is a shorthand for total = total + item, what is the value of item? Its a string (a item/product the customer wants to buy), string + integer results in an error

besides, we want to add the price of item to total, not the item itself. Which is why we need prices dictionary to get price of item


#3

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