A Day at the Supermarket - trying to understand the code



There are two things I am stuck at.
1. I looked at questions posted and saw that my code was missing below.

stock[item] = stock[item] -1

I am not quite sure what this line of code does. I understand that the value of the stock dictionary is subtracted by 1 and is updated to the stock value. But this still does not help me to understand what this code does. Any explanation would be very much appreciated!

  1. I am getting an error below once I execute the code.

compute_bill(['apple']) returned 0 instead of 2

Thank you for your help in advance!

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:
        if stock[item] > 0:
            total = total + prices[item]
            stock[item] = stock[item] -1
    return total
print compute_bill(shopping_list)


item is the key to an item in the stock dictionary. The associated value is a quantity. That line subtracts 1 from the stored quantity for that item.

Is this the lesson before the one where we subtract 1 from stock items?


Thanks for your reply.
It is the Making a Purchase lesson.
Unfortunately, I still don't understand why subtracting 1 from the stored quantity is necessary for this lesson.


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.

There is no need to include stock in this exercise.


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