How to fix the math in this function?


The error that I receive is "compute_bill(['apple']) returned 7.5 instead of 2". I'm not exactly sure how this even happens (maybe i'm just over thinking it).

I expected that when I replaced the original total variable in the new function compute_bill that 0+(whatever price here) would occur. Example: you take banana which has a price of $4 and that would be added to the original total of 0 (0+4). Then you given the new total variable.

Been stuck on this for probably an hour. How do you fix this? :sob:

 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(item):
    total = 0
    for item in shopping_list:
        total = total + prices[item]
    return total


you can pass a shopping list when calling function, so then the function parameter (item) will hold the shopping list, so you should loop over item.

the exercise will call the function by passing multiply list, it would be a bit boring if your function only works for one fixed shopping list


Thank you! I didn't realize that having the parameter as "item" would cause that. Changed it to shopping_list and it worked like a charm!


but do you now understand how it works?


50/50 on it. Would you mind explaining a little more?


when you call a function, you pass a argument, which is then stored in the function parameter, for example with shopping_lists you could do something like:

def compute_bill(items):
    total = 0
    for item in items:
        total = total + prices[item]
    return total
print compute_bill(['apple'])
print compute_bill(['orange'])
print compute_bill(['banana'])
print compute_bill(['apple','banana'])

this allows you to call the function with different shopping list, and for all shopping list compute_bill can calculate the total cost


Ahhh, ok. I was getting confused. I must have misread it or something.


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