Python :10.12:-Stocking Out


Good Morning Friends,I am stuck at :
Can anybody show my mistake.Following is my code:

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):
    for i in food:
        if i>stock[i]:
            total += prices[i]
    return total

I get following error message:

Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in 9 instead of the correct 7

Isn't the answer supposed to be 9 .(the addition of "apple"+""orange""+"pear")Plz explain.Thanks in advance


why are you checking i>stock[i] ?what does i contain?


Aren't we suppose to check presence of item"i" in stock


yes,we do . but what are you checking actually? what does i contain?


I get it now we should check the presence of item "i" by checking the stock value is greater than zero.

if stock[i]>0:
            total += prices[i]

But I am bit still confused.what is actually going on
On Execution
1)Interpreter goes in stock dictionary
2)How does it actually determines the presence of item
3)What will happen if the item is not present


glad , you sloved :slight_smile:


thank you help me so much


i is item. you would need to use item, or a letter like i.


total = 0
    for i in food:
        if stock[i]>0:
            total +=prices[i]
    return total

Lets go through it

First it loops through the food.what's food? simply food is the argument you pass.suppose you pass ['apple'] as an arugument that is a list contains one item only.
First iteration:
if stock[i]>0:
here i is apple so it is same as stock['apple'].it contains 0(the value of apple in stock dictionary is 0)

simpy condition is false(0>0). now here loop will be end too because there is no more item in the it'll return 0(total=0)

i hope you've understand now.try to call with more arguments so that you can understand better :slight_smile:


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