11. Making a Purchase. Brainless user needs help


#1

Task:

Define a function compute_bill that takes one argument food as input.
In the function, create a variable total with an initial value of zero.
For each item in the food list, add the price of that item to total.
Finally, return the total.
Ignore whether or not the item you're billing for is in stock.

Note that your function should work for any food list

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 = total + item
    return total

print compute_bill(shopping_list)

Error

Traceback (most recent call last):
  File "python", line 24, in <module>
  File "python", line 21, in compute_bill
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Me
Don't f*** understand what's the f**** is wrong. Thank You.


#2

item is a product ("apple", "banana"), your food function parameter can contain a list of products (look at shopping_list, you could supply this list as argument)

You will need to get from item to price (given you want to add price to total), maybe you can use your prices dictionary?


#3

in your code "item" is str instead of int. You should get price using price list.

put "prices[item]" instead of item. "total = total + prices[item]"


#4

Rewrited code:

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

print compute_bill(shopping_list)

Still same error:

Traceback (most recent call last):
  File "python", line 24, in <module>
  File "python", line 21, in compute_bill
TypeError: string indices must be integers, not dict

I DONT UNDERSTAND WHY
item[prices]
HE (PYTHON INTERPRETER) COUNTS AS STRING!


#5

Rewrited code:

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

print compute_bill(shopping_list)

Still same error:

Traceback (most recent call last):
  File "python", line 24, in <module>
  File "python", line 21, in compute_bill
TypeError: string indices must be integers, not dict

I DONT UNDERSTAND WHY
item[prices]
HE (PYTHON INTERPRETER) COUNTS AS STRING!


#6

ofarukvural gave you the solution?

as you can see:

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

print compute_bill(shopping_list)

item are products, which we can use as key to retrieve price value from our prices dictionary:

dictionaryName[keyName]

#7

Oh my, this worked. Thank You so much, im almost lost my mind.


#8