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


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


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


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



        return total

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


So, what should be the alternative


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?


Thanks a lot. it worked for me