A day at the supermarket - unexpected loop output


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

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

https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/something-of-value-?action=lesson_resume&link_content_target=interstitial_lesson

<In what way does your code behave incorrectly? Include ALL error messages.>
orange
price: 1.5
stock: 32
48.0
45
24
0
0.0
pear
price: 3
stock: 15
48.0
45
24
0
0.0
banana
price: 4
stock: 6
48.0
45
24
0
0.0
apple
price: 2
stock: 0
48.0
45
24
0
0.0

<What do you expect to happen instead?>
I would expect to just show 4 outputs with the correct value. Instead, it prints 8 outputs.

prices = {
  "banana" : 4,
  "apple"  : 2,
  "orange" : 1.5,
  "pear"   : 3,
}
stock = {
  "banana" : 6,
  "apple"  : 0,
  "orange" : 32,
  "pear"   : 15,
}

for key in prices:
  print key
  print "price: %s" % prices[key]
  print "stock: %s" % stock[key]
  
 
  for key in prices:
  		total = 0.
   		print prices[key]*stock[key]
    		total += prices[key]*stock[key]
  print total

#2

given your two loops are identical, one loop should be enough?

You nested the loops, this will create quit a lot of output, given the second (inner) loop runs all its iterations (4) the first loop iterates, so the inner loop makes a total of 16 iterations (4x4)

you should declare total outside the loop, so that total doesn’t get overwritten with zero every iteration of the loop, so you can get the total cost of the stores entire stock


#3

Thanks a lot @stetim94. I totally ignored the fact that my second “for” loop was nested in the first one!
Thanks :slight_smile:


#4