A day at the super market



The instructions are below:
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.

so my code is supposed to take the value of the prices list and add them all together and return final value (function compute_bill)

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

In stead I keep getting the error:

Oops, try again.
compute_bill(['apple']) returned 10.5 instead of 2


While your code takes food as input it doesn't actually do anything with it. Right now your code is looping through prices and adding the price of each item to the total. What it should do instead is loop through food and add each item from food to the total.


I dont think I quite understand then, I thought the goal of this exercise was to add all the item prices and set it to the "total"


Yeah the instructions are a little confusing, but what they want is a function that can take any list of food items, loop through the list it is given and output the total. For example if I ran compute_bill(['apple', 'pear'])
I would except it to output the total to be 5.


My code was:

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

In your code, you used

but you should use key in food (actually, you don't need key, it's just what I used instead of item).
Also, to make it easier, use += instead.
Hope this helped.


In your for loop makes sure it is in food instead

for key in food:

that being said it could also be

for item in food:

but that depends on what you want, i think in this case it would be easier to use 'item'

and make sure you print the compute bill with the argument of shopping_list at the end

print compute_bill(shopping_list)


I got it to work thank you everyone! Much obliged!


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