Finding the keyword for looping


This is most likely a very stupid question, but I’m having trouble understanding how the value used as [key] is found/determined when looping/using for…in.

Example from “Keeping Track of the Produce” below. How should I know that the correct word to use is ‘food’ and not for example item or fruit. I assumed I can use any word, but that clearly didn’t work.

prices = {“banana”: 4,“apple”: 2,“orange”: 1.5,“pear”: 3}

stock = {“banana”: 6, “apple”: 0, “orange”: 32, “pear”: 15}

for food in prices:
print food
print “price: %s” % prices[food]
print “stock: %s” % stock[food]

Thank you already for patience with this question if it seems too stupid.


you define food in the loop, here:

for food in prices:

then python will assign the dictionary keys to food, so you can use them in the loop

if you change food in the for loop to something else, then this variable is used to assign the keys too.


Thanks! I do know how to define the loop, but unsure why in the exercise the loop had to be defined with ‘food’ and no other word, such as “for fruit in prices” worked. If only specific words can be used, how do you figure out what to use to define the loop?


In practice, there’s no reason why you couldn’t have defined the loop as for fruit in prices. You can name the variable holding the current item practically whatever you want, but in this instance the exercise wanted you to use food. (Obviously, if you’ve got a variable somewhere else in the code called fruit you wouldn’t be able to use it as the variable in your loop, as an example.)

Using fruit rather than food may have caused you to fail the exercise, though. This is not because the code was wrong or invalid, but because the instructions (and consequently the back-end verification process) are expecting you to use a specific definition.

Does that make sense?


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