Why does this work? (for item in food)



<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>
why does for item in food work? i thought that for item in references a list or dictionary, yet the list and dictionary’s are called prices and stock and shopping_list.
i get that i’ve defined compute_bill (food) , but how does it know that i’m talking about stock and prices on the loop? , sorry if i’m not making myself clear i’m struggling to understand the logic of how the code knows that looping through food actually loops through stock and prices


hopping_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:
if stock[item] > 0 :
total += prices[item]
stock[item] -= 1
return total

<do not remove the three backticks above>


Look here:

In our function, we have one parameter, food. It’s just a placeholder when calling a function and adding an argument. So if I called my function anywhere outside of it after defining it like this:

print compute_bill(prices)

prices is the argument, it takes place of all the food placeholders in your function. It doesn’t replace them physically, but in the background, Python knows that prices is food, and anything that happens to the food parameter will happen to prices (or whatever argument you choose). Basically, the argument will take place of food. Do you get what I mean?


so definitions in the same script always know any lists or dictionary’s present ? and the temporary argument of food only exists within the following indented text?
thanks for the help


In all of your code, functions, all of that stuff, so yep. A thing to remember though:

If I defined my function after my dictionary, then called anywhere before the line where it was defined, I would get a NameError. So, don’t call your function in a place before it was defined in your line of code. :slight_smile:

Yes, if I called food outside of my function, I would get an error (NameError) saying food is not defined.

You’re welcome! :smiley:


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