8/12 Keeping Track of the Produce



I dont have an error but I dont understand why Python recognized “food” as the variables of prices and stocks… How?? :o


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]
<do not remove the three backticks above>


food is define/declared in the for loop, python will assign all keys in dictionary to the loop iterator (food), after being assigned, the loop executes, then assign the next key to the loop iterator and so on


Thanks! so If I would write :

for random in prices:
print random

It would work as well?


yes, essentially the variable is defined in the loop, so just like regular variables it can have any name you like, but it would be good practice to give it a logic name so you know what the variable does


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