Keeping Track of the Produce


#1

So I think I have the right code but python is trowing me this error.

my code =

for key in price:
  if key == "apple":
   print  key 
   print "price: %s" % price[key]
   print "stock: %d" % stock[key]


apple
price: 2
stock: 0

Check what your code prints for orange. It doesn't look quite right!
for key in price:
  if key == "orange":
   print  key 
   print "price: %s" % price[key]
   print "stock: %d" % stock[key]


orange
price: 1.5
stock: 32

These are the correct answers but I still get an error , can somebody explain why ?


#2

Hi @aovalle,

Why are you using if statements such as this? …

 if key == "apple":

You need to output all the items, so you don’t need a conditional block there.


#3

Because we only want to find the information about apples, right?
without the if statement I get all of the items in my list


#4

You need to find the information about all of the items. One of the items will be handled by each iteration of the loop, until all of them have been output. You don’t need to do anything like this …

  if key == "orange":

#5

mmm so for this exercise I am required to only have three printed statements that look like this

apple
price: 2
stock: 0

I am not sure how to get here without an if statement.


#6

The for loop with three print statements is sufficient to get all the items output. The loop will iterate once for each item, so it will iterate four times. During each iteration, all three print statements will execute. However, if you use an if statement, such as the ones you have, it will prevent some of the items from getting output.

You should have a dictionary named prices. Therefore, your for loop header should be …

for key in prices:

However, you have …

for key in price:

This statement should refer to the prices dictionary …

   print "price: %s" % price[key]

Therefore, it should be changed to …

   print "price: %s" % prices[key]

With a correct for loop header and three correct print statements, all the data will be output correctly.


#7

Got it ! I was stuck because I thought only three outputs needed to show up in the console. Thank you very much !


#8