Please help me understand? :)


A Day at supermarket: Task 11 making a purchase

Hi I have my code pasted below but I'm just wondering what it means, I completed the task however don't understand what the code is doing, is their any chance that someone could explain to me in simple terms what the code is doing. Thank you :smile:

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


If you know what it's supposed to be doing in general terms, then you should be able to map the code to what you know it should be doing, right?


You've created a loop, which is iterating over a food list. For each item of list (food), there is getting it's price from prices dictionary and added to total variable.
When for loop ends, you return sum of prices of all items from food list.

Let's assume:

prices = {
    "banana": 3,
    "apple": 1,
    "orange": 1.5,
    "pear": 3.5

shopping_list = ["banana", "apple"]

If you call compute_bill(shopping_list), your function will:
1. declare a variable total = 0
2. run for loop for every item in your shopping_list list
2.1. item = "banana"
2.1.1. total += prices[item] == total += prices["banana"] == total += 3. Now total = 3
2.2. item = "apple"
2.2.1. total += prices[item] == total += prices["apple"] == total += 1. Now total = 4
2.3. for loop ends here, because you have only 2 items in list.
3. function returns total variable, so it returns 4.


Thank you for your help :slight_smile: