Calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in 0 instead of the correct 7


#1

This 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
}

def compute_bill(food):
    total = 0
    for a in food:
        if  stock[a]> 0:
            total = prices[a] + total
            stock[a] -= 1 
        return total
        Any help from the viewers side will be highly appreciated

#2

a function ends the moment a return keyword is reached

so, your function ends in the first iteration of your loop, so it won't be able to calculate the correct price for customer when customer wants to buy 2 or more products


#3

i am not so pro with programming. Will you be kind enough to pinpoint my mistake?


#4

sure:

        return total

there is your mistake. You want to return the total after the loop has successful calculate the total cost.


#5

So, what should be the alternative


#6

covered that as well. I now covered your mistake (your function ends to early, the function ends in the first iteration of the loop rather then after the loop)

In python, what determines if something is nested inside or outside a loop?


#8

Thanks a lot. it worked for me


#9