11. making a purchase


#1



why is this happening please help

Oops, try again. compute_bill(['banana', 'apple', 'orange', 'pear']) returned 4 instead of 10.5


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:
        total += prices[item]
        return total


#2

Try aligning the return total with the for statement. Like this:

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

Python takes indentation very seriously


11.making a purchase
#3

thanks so much it works


#4

but do you also understand why it works? Why changing the indent resolves the issue?


#5

hi,
kindly explain
thank you.


#6

a function ends the moment a return keyword is reached, if you have this:

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

the return keyword is reached in the first run of the loop, the function ends. By changing the indent, the whole for loop runs, allowing everything to be added to total instead of just one item


#7

Thank you very much!


#8

thank you so much,

i've understood


#9

I understand now thanks


#10