Stuck please help


#1



https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096

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


I expected to complete the exercise. :smiley:


shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "orange": 1.5,
    "apple": 2,
    "pear": 3
}

# Write your code below!
def compute_bill(food):
    total = 0
    for food in prices:
        total = total + prices[food]
        return total
.


#2

Which result do you agree with? (Do you agree that your function misbehaves? - if yes, investigate code, if no, read instructions)

I suggest using prints to find out what your code does to obtain the result 1.5 - which fruits does it look up, which prices does it use, what's the total sum after adding each fruit's price and so on, whatever you think is useful information


#3

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

The problem is your "return", return the result to the function, not to the "for" loop.


#4

def compute_bill(food):
____total = 0
____for food in prices:
________total = total + prices[food]
____return total


#5

Hi,
thanks for the suggestion but that brings up another error.

Oops, try again. compute_bill(['apple']) returned 10.5 instead of 2
I think you were right in pointing that out, and I think my code should work now. I really don't understand why it misbehaves.


#6

Hi,
I tried printing every step, but i just got the same error and nothing was printed.


#7

Found the solution.

Write your code below!

def compute_bill(food):
total = 0
for key in food:
total += prices[key]
return total
Because it must work with any list I had to replace prices with food.


#8

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