Explanation of whats happening?



So my code is working but I don't understand why it works. I basically looking for a explanation of a function and how it is working with this loop? Can someone please explain?

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


We write code from a basis of understanding. This question is one that we cannot understand. Are you asking us to explain code from another source?


Um Im not really sure, I guess I should have been more specific. I suppose what I want to know how the function is working and what the argument actually does. Im confused how the argument food has anything to do with the dictionary's.


The food parameter is a locally declared variable that receives the caller argument. In this case, the argument is 'shopping_list', but inside the function, it is referred to by its local name, food.

The relationship is one of similarity.

food item  => 'banana'

prices key => 'banana'

stock key  => 'banana'


Thanks for explaining this mtf...I have the same mental block on the logic here. Are you saying that we don't need to explicitly make the connection between the list name "shopping_list" and the parameter "food"? That the relationship is formed because of the similarity between the keys and item?

Like the OP, my code eventually worked...but I still don't really understand how. I would have expected the "correct" code to looks something like this:

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


... contains strings that are found as keys in the prices and stock dictionaries. Keys are strings, also, so they match up. We have used a list to match up keys in a dictionary.

More importantly, we want our function to work with a variety of inputs. The parameter name should never match the name of the object being passed to the function unless there is a specific reason for doing so. It can mess with things.

The function, to be independent of global constraints has a local variable, gvein in the parameter,

def func(x):

When we call upon this function with some argument, x is the local representation of it.


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