11. Making a Purchase. I don't understand functions


Hello, I'm currently starting Python (it's my first language too) and I'm kind of confused right now, and I can't get past this exercice. I'm doing the "A Day at the Supermarket" more specifically "Making a Purchase". Here.

I'm having a hard time understanding fuctions, at least that should be the problem since I haven't been able to succeed here.

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 price in food:
        total += price
    return total

First off, I do not understand how Python is supposed to understand that the fuction I'm writing has to do something with the dictionaries, since I no where are they mentioned inside the function, yet the error code is the following:

Oops, try again. compute_bill(['apple']) resulted in a TypeError: unsupported operand type(s) for +=: 'int' and 'str'

which means that somehow the function is running either "stock" or "prices".

From what I understand, "price" in the function is a string since it says "for +=: 'int' and 'str'"

So what is the problem here? What am I doing wrong and how do I fix it?


This isn't quite right. You want to add the prices of each food in the price dictionary, so that line should be like this:

total += prices[price]

Message me if you still need more help after that. :slight_smile:

-- @chipjumper36731


So that's the way the function calls for the "prices" dictionary? I see. Why does it still call it without having that there, giving me the apple thing?


Well, "compute_bill" is the function name, and the error message is basically saying that when the lesson checker inserts "apple" in the function, then that is what the error comes up as. :slight_smile:


thank you for the help


Welcome :slight_smile:


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